我正在创建一个VBA宏来将过滤后的数据范围提取到模板中。我一直收到Range not Defined错误。
我尝试在Excel中使用宏录制工具,但当我尝试将其与我编写的代码一起使用时,它会立即中断。
'filter to correct range
ActiveSheet.Range("$A$1:$X$1647").AutoFilter Field:=14, Criteria1:="-333"
ActiveSheet.Range("$A$1:$X$1647").AutoFilter Field:=17, Criteria1:= _
"rslicenceHolder"
'Copy Results and Paste into Template
Range("A1082:T1082").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Active.Workbook("Sample Chasers Template .xlsx").Activate
Sheets("RS Chasers").Select
Range("A4").Select
ActiveSheet.Paste
答案 0 :(得分:2)
下面的代码会将Filtered表格从你的表格复制到" RS Chasers"表格和#34;样本追踪器模板.xlsx"工作簿。
注意:尽量避免使用ActiveSheet
,Select
和Selection
,而是使用完全限定的对象。
<强>代码强>
Option Explicit
Sub CopyFilterData()
Dim Rng As Range, VisRng As Range
With Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
Set Rng = .Range("$A$1:$X$1647") ' <-- better use referenced sheet than ActiveSheet
Rng.AutoFilter Field:=14, Criteria1:="-333"
Rng.AutoFilter Field:=17, Criteria1:="rslicenceHolder"
Set VisRng = Rng.Resize(Rng.Columns(17).SpecialCells(xlCellTypeVisible).Cells.Count, 20).Offset(1, 0) '<-- set visible Range to filtered range
VisRng.Copy Destination:=Workbooks("Chasers Template.xlsx").Worksheets("RS Chasers").Range("A4") '<-- copy >> paste in 1 line
End With
End Sub
答案 1 :(得分:0)
您对工作簿的引用&#34; Sample Chasers Template .xlsx&#34;是不正确的。试试这个:
ActiveSheet.Range("$A$1:$X$1647").AutoFilter Field:=14, Criteria1:="-333"
ActiveSheet.Range("$A$1:$X$1647").AutoFilter Field:=17, Criteria1:= _
"rslicenceHolder"
'Copy Results and Paste into Template
Range("A1082:T1082").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Active.Workbook(Sample Chasers Template .xlsx").Activate
Workbooks("Sample Chasers Template .xlsx").Activate
Sheets("RS Chasers").Select
Range("A4").Select
ActiveSheet.Paste
我应该提一下,尽管您仍然在复制并粘贴A1082:T1082并向下,无论您的过滤结果实际位于何处。您可能还想用以下内容替换:
Range("A1:T1").Select
Range(Selection, Selection.End(xlDown)).Select
答案 2 :(得分:0)
已编辑以包含OP
指定的实际工作簿名称假设您要复制/粘贴所有列A到T过滤的单元格,不包括标题:
Dim repWB as Workbook, tempWb as Workbook
Set tempWb = Workbooks.Open("C:\Desktop\Template.xlsx") '<--| change "C:\Desktop\" to actual path of template workbook
Set repWB = Workbooks.Open("C:\Desktop\Report.xlsx") '<--| change "C:\Desktop\" to actual path of report workbook
With repWB.Range("$A$1:$X$1647")
.AutoFilter Field:=14, Criteria1:="-333"
.AutoFilter Field:=17, Criteria1:="rslicenceHolder"
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Resize(.Rows.count - 1, 20).Offset(1).SpecialCells(xlCellTypeVisible).Copy tempWb.Sheets("RS Chasers").Range("A4")
.Parent.AutoFilterMode = False
End With