-
Cells(count_row, count_col)
不是表的右下角单元格,因为表不是从A1开始的。对于您的场景,count_row=8,count_col=4。自动滤波器适用于A4:D8范围
,排除Region所在的所需行
ASIA (EX. NEAR EAST)
.
og.Range(Cells(4, 1), Cells(count_row, count_col))
How to avoid using Select in Excel VBA
Microsoft文档:
Range.Resize property (Excel)
Sub copy_data()
Dim count_col As Long
Dim count_row As Long
Dim og As Worksheet
Dim wb As Workbook, sht As Worksheet
Dim region As String
Const START_CELL = "A4"
Set og = Sheet1
region = og.Cells(1, 1).Text
Set wb = Workbooks.Add
Set sht = ActiveSheet
sht.Name = region
With og.Range(START_CELL)
count_col = .End(xlToRight).Column
count_row = og.Cells(og.Rows.Count, 1).End(xlUp).Row - .Row + 1
.AutoFilter Field:=2, Criteria1:=region
.Resize(count_row, count_col).SpecialCells(xlCellTypeVisible).Copy
End With
sht.Cells(1, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
og.ShowAllData
og.AutoFilterMode = False
End Sub
-
如果表是
sperated
范围(即表被空白行和列包围),您可以使用
CurrentRegion
.
Microsoft文档:
Range.CurrentRegion property (Excel)
With og.Range(START_CELL)
.AutoFilter Field:=2, Criteria1:=region
.CurrentRegion.SpecialCells(xlCellTypeVisible).Copy
End With