【问题标题】:Method Range of object worksheet failed when copying dynamic range复制动态范围时对象工作表的方法范围失败
【发布时间】:2019-02-19 12:30:56
【问题描述】:

我有一个遍历一系列单元格的循环,如果满足条件,我将相关数据复制到一个工作表,如果不满足另一个工作表。 我在动态使用范围以进行复制时遇到问题。

我尝试以 2 种不同的方式引用范围,但得到相同的错误

For i = 2 To lastRow
     Set found= WC.Range("O1:O" & LastInList).Find(SL.Range("G" & i))

    If Not (found Is Nothing) 
        SL.Range(Cells(i, 1), Cells(i, 3)).Copy Destination:=WC.Range("A" & WCEmptyRow) 'ERROR here
    Else
        'do something
    End If
Next i

也试过了:

SL.Range("A" & i, "C" & i).Copy Destination:=WC.Range("A" & WCEmptyRow) ' ERROR here

我应该如何引用 I 行中的单元格以便复制它们?

【问题讨论】:

  • 你测试 foundAH 只是为了你 Set found。我强烈建议始终激活Option Explicit 以避免此类拼写错误:在 VBA 编辑器中转到 ToolsOptionsRequire Variable Declaration。 • 还要为Cells(i, 1) 指定一个工作表,否则它可能与SL.Range 不在同一个工作表中。 • 如果您总是出现错误,请告知在哪一行,否则我们必须猜测。 • 还要确保WCEmptyRowLastInList>0
  • @Pᴇʜ 谢谢,我有明确的选项,上面是一个错字(我已修复)。我按照您的建议添加了工作表。我仍然收到错误消息。
  • 你需要在这里修复它SL.Range(Cells(i, 1), Cells(i, 3)).Copy所以它变成SL.Range(SL.Cells(i, 1), SL.Cells(i, 3)).Copy
  • 然后请检查并告诉WCEmptyRowLastInList的值。例如。使用Debug.Print WCEmptyRow, LastInList 将其输出到即时窗口。我敢打赌WCEmptyRow 不是>0 或最后一行1048576
  • @Pᴇʜ 谢谢!问题确实是 WCEmptyRow (不是负数,太大了,我数错了,然后在最后可能的行上加了 1)。再次感谢。

标签: excel vba


【解决方案1】:

foundAH 是什么?它不在代码中。确保检查是针对If Not (foundAH Is Nothing)。为了避免未声明的变量,请遵循 cmets 中 @PEH 的 Option Explicit - 在 VBA 编辑器中转到工具 › 选项 › 需要变量声明

此外,代码位于number 1 error in the VBA tag in SO - not explicitly declaring parent worksheets。查看修改后的代码中的点:

For i = 2 To lastRow
    Set found= WC.Range("O1:O" & LastInList).Find(SL.Range("G" & i))

    If Not (found Is Nothing) 
        With SL
            .Range(.Cells(i, 1), .Cells(i, 3)).Copy Destination:=WC.Range("A" & WCEmptyRow)
        End With
    Else
        'do something
    End If
Next i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    相关资源
    最近更新 更多