Excel VBA:下标超出范围代码修复

时间:2018-10-05 13:12:51

标签: excel vba excel-vba

我在行中不断出现下标超出范围的错误

Sheets("Dump").Select

如何调整代码以消除错误?并有一种方法可以调整它以删除.Select

Sub UploadData()
'open the source workbook and select the source
Dim wb As Workbook

Workbooks.Open Filename:=Sheets("Instructions").Range("$B$4").value
Set wb = ActiveWorkbook
Sheets("Invoice Totals").Select

'copy the source range
Sheets("Invoice Totals").Range("A:R").Select
Selection.Copy

'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("A2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=False

' copy the source range
Sheets("Lease & RPM Charges").Range("A:AH").Select
Selection.Copy

'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("T2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=False

'copy the source range
Sheets("MMS_Service_And_Repairs").Range("A:R").Select
Selection.Copy

'select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Dump").Select
Sheets("Dump").Range("BC2").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=False

'close the source workbook
wb.Close

End Sub

1 个答案:

答案 0 :(得分:0)

编辑(已修复问题),尝试一下...(已在模拟数据上测试)。

Sub UploadData()

Dim wb As Workbook
Dim lRow As Long, lRow2 As Long, lRow3 As Long 'Set lastrow for each source worksheet
Dim rng As Range, rng2 As Range, rng3 As Range 'Set range for each source worksheet

'open the source workbook using the filename in cell B4(I'm making an assumption that the
'source workbook is located in the same folder as the Thisworkbook
Set wb = Workbooks.Open(Filename:=Sheets("Instructions").Range("$B$4").Value)

With wb
    With .Sheets("Invoice Totals") 'Copy the range on this ws and paste to "Dump" in dest ws
        lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        Set rng = .Range("A1:R" & lRow)
            rng.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("A2")
    End With

    With .Sheets("Lease & RPM Charges") 'Copy the range on this ws and paste to "Dump" in dest ws
        lRow2 = .Cells(.Rows.Count, 1).End(xlUp).Row
        Set rng2 = .Range("A1:AH" & lRow2)
            rng2.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("T2")
    End With

    With .Sheets("Invoice Totals") 'Copy the range on this ws and paste to "Dump" in dest ws
        lRow3 = .Cells(.Rows.Count, 1).End(xlUp).Row
        Set rng3 = .Range("A1:R" & lRow3)
            rng3.Copy Destination:=ThisWorkbook.Sheets("Dump").Range("BC2")
    End With

    With ThisWorkbook.Sheets("Dump").UsedRange
       .Value = .Value  'Sets all the data in the usedrange to values only
    End With
End With

wb.Close 'close the source workbook

End Sub