合并3个VBA代码并将其作为单个代码运行

时间:2019-01-16 06:17:08

标签: excel vba

我有3个VBA代码,它们在3张不同的纸上执行相同的操作。我想将所有3个代码作为一个代码运行。

我是这样做的,但是它给出了

  

应用程序错误(错误1004)

Sub lastRow()
    Dim wsS1 As Worksheet 'Sheet1
    Dim wsS2 As Worksheet 'sheet2
    Dim lastR As Long, lastC As Long

    Set wsS1 = Sheets("Instru Input")
    Set wsS2 = Sheets("Final Input")
    Set wsS3 = Sheets("FinalInputFile")

    With wsS1
        lastR = .Range("A" & .Rows.Count).End(xlUp).Row - 4
    End With

    With wsS2
        lastC = .Cells(3, Columns.Count).End(xlToLeft).Column
        Range(.Cells(3, 1).Address, .Cells(3, lastC).Address).AutoFill 
        .Range(.Cells(3, 1).Address, .Cells(lastR, lastC).Address)
    End With

    with wsS1
        lastR = .Range("A" & .Rows.Count).End(xlUp).Row - 4
    End With

    With wsS3
        lastC = .Cells(3, Columns.Count).End(xlToLeft).Column
        Range(.Cells(3, 1).Address, .Cells(3, lastC).Address).AutoFill 
        .Range(.Cells(3, 1).Address, .Cells(lastR, lastC).Address)
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

请注意,您所有的Range都必须以.Range之类的点开头,否则它们不会使用With语句。您的Range中的某些人缺少点。

所以不是

With wsS2
    lastC = .Cells(3, Columns.Count).End(xlToLeft).Column
    Range(.Cells(3, 1).Address, .Cells(3, lastC).Address).AutoFill 
    .Range(.Cells(3, 1).Address, .Cells(lastR, lastC).Address)
End With

应该是

With wsS2
    lastC = .Cells(3, Columns.Count).End(xlToLeft).Column
    .Range(.Cells(3, 1).Address, .Cells(3, lastC).Address).AutoFill .Range(.Cells(3, 1).Address, .Cells(lastR, lastC).Address)
End With