excel 下标超出范围-运行时错误“9”

dhxwm5r4  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(223)

我正尝试从4个工作表中的某列获取数据并将它们组合在一起。行数可能会更改,因此我需要自动执行此操作。所有这些工作表都包含在一个工作簿中。此工作簿已打开。
我正在使用这段代码来尝试完成这个任务,但是我的下标超出了范围。我相信这告诉我,我引用了数组之外的某个地方,但是我似乎找不到它。调试将我指向For循环,但是我觉得它似乎没问题?每个数组元素都是我工作簿中的不同工作表。每个工作表中的数据只是一个球员姓名。

Sub CopyRange()
    Dim bottomD As Integer
    Dim ws As Worksheet
    For Each ws In Sheets(Array("Batters (OF) - Bat X", "Batters (SS) - Bat X", "Batters (3B) - Bat X", "Batters (2B) - Bat X"))
        ws.Activate
        bottomD = Range("Batters (OF) - Bat X" & Rows.Count).End(xlUp).Row
        Range("A2:D" & bottomD).Copy Sheets("Batters - Bat X").Cells(Rows.Count, "Batters (OF) - Bat X").End(xlUp).Offset(1, 0)
    Next ws
End Sub
eqqqjvef

eqqqjvef1#

从不同工作表复制相同列

Sub CopyColumns()
    
    Dim swsNames(): swsNames = Array( _
        "Batters (OF) - Bat X", _
        "Batters (SS) - Bat X", _
        "Batters (3B) - Bat X", _
        "Batters (2B) - Bat X") ' to easier check the spelling
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim dws As Worksheet: Set dws = wb.Sheets("Batters - Bat X")
    Dim dfCell As Range
    Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
    
    Dim sws As Worksheet, srg As Range, sLastRow As Long
    
    For Each sws In wb.Worksheets(swsNames)
        sLastRow = sws.Cells(sws.Rows.Count, "A").End(xlUp).Row
        Set srg = sws.Range("A2:D" & sLastRow)
        srg.Copy dfCell
        Set dfCell = dfCell.Offset(srg.Rows.Count)
    Next sws

    MsgBox "Columns copied.", vbInformation

End Sub

相关问题