【发布时间】:2015-07-26 21:23:28
【问题描述】:
我正在编写一个 VBA 宏,它复制一组数据,应用一些过滤,然后将过滤后的数据复制到下一个可用行。我的问题是最后一行“copyRange.SpecialCells(xlCellTypeVisible).Copy GAR070 ....”有时有效,有时不会出现错误:运行时错误'1004':对象'_Worksheet'的方法'范围'失败了。
如果我随后将对 GAR070 工作表对象的引用更改为 Sheets("GAR070") 我最终会出现运行时错误“1004”:应用程序定义或对象定义错误。
因为这有时对我有用,有时我不知道它是否与我打开的其他工作簿有关?或者当我声明对象时发生了什么?
我的代码还有很多内容,但我没有将其包含在此处,因此您不必通读所有内容,但是如果您怀疑那里可能发生了某些事情,我很乐意对其发表评论。
我之前在这个网站和其他网站上查看过如何做到这一点,这就是我最初使用这种方法找到的方法。
如果我遗漏了什么,请告诉我,非常感谢:)
Sub Check_for_specials()
Dim GAR070 As Worksheet
Dim LRowred As Long
Dim filterRange As Range
Dim copyRange As Range
Dim newrow As Long
Dim wb as Workbook
Application.ScreenUpdating = False
Set wb = ActiveWorkbook
Set GAR070 = wb.Sheets("GAR070")
'filter for "Y" in last column, copy this data and paste into the next available row
With GAR070
LRowred = .Cells(Rows.Count, "A").End(xlUp).Row
' turn off any autofilters that are already set
.AutoFilterMode = False
' the range that we are auto-filtering (all columns)
Set filterRange = .Range("A1:O" & LRowred)
' the range we want to copy (only columns we want to copy)
Set copyRange = .Range("A2:N" & LRowred)
' filter range based on column O
filterRange.AutoFilter field:=15, Criteria1:="Y"
' copy the visible cells to our target range
newrow = LRowred + 1
copyRange.SpecialCells(xlCellTypeVisible).Copy GAR070.Range(Cells(newrow, 1), Cells(newrow + 1, 14)) ' seems very volatile...
Application.ScreenUpdating = True
End sub
【问题讨论】:
标签: excel filter copy paste vba