添加Worksheet.name后,VBA工作表不循环

时间:2013-07-22 17:12:37

标签: vba loops

我有一个在第一个工作表上正常运行的宏,但在尝试转到下一个工作表时崩溃了。我得到运行时错误1004应用程序定义或目标定义的错误。

我的代码之前返回了单元格的值,它循环好了。我更改了代码,因为源数据中有空白单元格,当它复制并粘贴到我的主数据表时,它会留下一个空白单元格来抵消我的数据。

在我更改宏以拉取单元格地址而不是值之后,它停止了循环。

我的代码是

Sub Test()

Dim imaxrow As Double
Dim i As Double
Dim wscount As Double

wscount = ActiveWorkbook.Worksheets.Count


For i = 2 To wscount
    'Rows of data to be extracted
    imaxrow = 22 'Max rows
    'Use to offset columns to next dataset
        For Each e In Array(0, 11)
        'Starting row to copy data
        For irow = 10 To imaxrow
            If Worksheets(i).Cells(irow, 21 + e).Value = "" Then
                'Nothing in this cell.
                'Do nothing.
                Else
                ' Copy Cell data to mastersheet


                Worksheets("macro test sheet").Cells(Rows.Count, "F").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 21 + e).Address


                 Worksheets("macro test sheet").Cells(Rows.Count, "G").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 22 + e).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "H").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 23 + e).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "I").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 24 + e).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "C").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 4).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(irow, 3).Address



                Worksheets("macro test sheet").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(5, 1).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "D").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(6, 21 + e).Address


                Worksheets("macro test sheet").Cells(Rows.Count, "E").End(xlUp).Offset(1, 0) = "=" & Worksheets(i).Name & "!" & Worksheets(i).Cells(7, 21 + e).Address

            End If
        Next irow
        Next e
    Next i

End Sub

1 个答案:

答案 0 :(得分:0)

当您没有正确引用工作表名称时,会出现您描述的错误,在这种情况下,我认为它是一个可能包含空格的工作表名称。尝试用单引号或双引号括起工作表名称:

... "='" & Worksheets(i).Name & "'!" ...