【问题标题】:Excel VBA looping through multiple worksheetsExcel VBA循环遍历多个工作表
【发布时间】:2014-11-15 05:29:39
【问题描述】:

这里是 VBA 初学者,我正在处理的程序有点问题。

我需要从第一个工作表中复制 B 列中最后一个单元格的数据并将其粘贴到另一个工作表 xws 的 A 列中,然后对其他五个带有数据的工作表重复此操作。

这是代码,它不能按应有的方式工作:

Sub exercise()

    Dim ws As Worksheet
    Dim rng As Range
    'Finding last row in column B
    Set rng = Range("B" & Rows.Count).End(xlUp)

    For Each ws In ActiveWorkbook.Worksheets
        'Don't copy data from xws worksheet
        If ws.Name <> "xws" Then
            'Storing first copied data in A1
            If IsEmpty(Sheets("xws").[A1]) Then
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp)
            'Storing next copied data below previously filled cell
            Else
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            End If
        End If
    Next ws
End Sub

ws 有问题。引用,但是每当我将它放在 if 语句中的 rng 之前或范围之前(设置 rng = ...)时,我都会出错。

提前感谢您的任何指点。

【问题讨论】:

  • 当我从活动工作表启动宏时,我将相同的信息复制到工作表 xws 中的六个单元格 (A1:A6) 中,仅来自活动工作表。

标签: vba excel


【解决方案1】:

您应该为循环内的每个ws 声明rng,例如:

Sub exercise()
    Dim ws As Worksheet
    Dim rng As Range

    For Each ws In ActiveWorkbook.Worksheets
        'Finding last row in column B
        Set rng = ws.Range("B" & ws.Rows.Count).End(xlUp) '<~~ Moved inside the loop
        'Don't copy data from xws worksheet
        If ws.Name <> "xws" Then
            'Storing first copied data in A1
            If IsEmpty(Sheets("xws").[A1]) Then
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp)
            'Storing next copied data below previously filled cell
            Else
                rng.Copy Sheets("xws").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            End If
        End If
    Next ws
End Sub

正如您的代码现在一样,rng 将在您运行宏时指向 ActiveSheet,然后您的代码将在代码的每次迭代中复制相同的单元格。

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2013-08-17
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多