【问题标题】:Copy and paste visible cells only to variable row仅将可见单元格复制并粘贴到变量行
【发布时间】: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


    【解决方案1】:

    这有点令人困惑,因为你有

    With GAR070
    

    但没有 End With,所以我不知道你的 With 结束在哪里。

    这可能不是您遇到问题的根源,但这一行:

    copyRange.SpecialCells(xlCellTypeVisible).Copy GAR070.Range(Cells(newrow, 1), Cells(newrow + 1, 14))
    

    使用没有限定符的单元格。

    如果 End With 出现在此行之上并且 Cells(newrow,1) 指的是 GAR070 工作表上的地址,那么它应该是:

    copyRange.SpecialCells(xlCellTypeVisible).Copy GAR070.Range(GAR070.Cells(newrow, 1), GAR070.Cells(newrow + 1, 14))
    

    如果 End With 低于此行,则应为

    copyRange.SpecialCells(xlCellTypeVisible).Copy .Range(.Cells(newrow, 1), .Cells(newrow + 1, 14))
    

    这有意义吗?

    【讨论】:

    • 谢谢谢谢谢谢!它确实有效。并且完全有道理。抱歉回复延迟,我不得不回去工作测试一下。非常感谢:)
    • 我很乐意提供帮助。考虑接受我的回答,以便将问题标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2021-01-24
    相关资源
    最近更新 更多