对于VBA上的i循环函数,会出现“类型不匹配”编译器错误

时间:2017-12-25 01:58:07

标签: excel vba

我在下面的循环函数中遇到编译错误'type mismatch'。我试图在主工作表中组合多个工作表,这将有助于通过它们具有循环功能。任何帮助将不胜感激。

谢谢,

Public Sub combine2()
    Dim i As Worksheet
    For i = 1 To Worksheet.Count

        Worksheets(i).Select
        Columns("A:B").Select
        Selection.copy
        Sheets("sheet").Select
        Selection.End(xlDown).Select
        Selection.End(xlUp).Select
        ActiveSheet.Paste
        Range("A1").Select
        Selection.End(xlDown).Select
        Selection.End(xlDown).Select
        Selection.End(xlUp).Select

    Next i
End Sub

2 个答案:

答案 0 :(得分:2)

在第一行你声明变量" i"作为Worksheet类型的对象,然后你去分配一个数字的值。您无法做到,因为您明确表示它是一个工作表 - 而不是数字类型(例如整数)。这是一种类型不匹配。

它也应该是工作表 - 而不是工作表

Dim i As Integer
For i = 1 To Worksheets.Count

答案 1 :(得分:2)

下面的代码会将所有工作表(Sheet1除外)的A列和B列(字幕除外)中的所有内容复制到工作簿中的第一个工作表。你可能需要稍微调整一下才能做你真正想要的事情。

Public Sub combine2()

    Dim Master As Worksheet
    Dim Ws As Worksheet
    Dim Rng As Range
    Dim Rl As Long
    Dim i As Integer

    Set Master = Worksheets(1)
    Application.ScreenUpdating = False
    For i = 2 To Worksheet.Count
        Set Ws = Worksheets(i)
        With Ws
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
            Set Rng = Range(.Cells(2, "A"), .Cells(Rl, "B"))
            Rng.Copy
        End With

        With Master
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
            .Cells(Rl, "A").PasteSpecial xlValues
        End With
    Next i
    With Application
        .CutCopyMode = False
        .ScreenUpdating = True
    End With
End Sub