[英]VBA Dynamice Array subscript out of range
我对 VBA 很陌生,并尝试编写代码以将同一文件夹中的许多文件中的数据导入新工作簿。 我使用动态数组来更新数据,但仍然出现下标超出范围错误。 调试时出现Arr(1, 14) = RngInt(2, 1) - Sheets("A").Range("N" & R)
错误。您能帮我纠正错误,以便代码可以能够正确 function 吗? 非常感谢。 这是我的代码:
Sub CopyDataBetweenWorkbooks()
Dim Arr(), R As Long, FinalRow As Long, x As Integer
Dim wbSource As Workbook
Dim shTarget As Worksheet
Dim shSource As Worksheet
Dim strFilePath As String
Dim strPath As String
' Initialize some variables and ' get the folder path that has the files
Set shTarget = ThisWorkbook.Sheets("A")
strPath = ThisWorkbook.Sheets("A").Range("Path") & "\"
' Make sure a folder was picked.
If Not strPath = vbNullString Then
' Get all the files from the folder
strfile = Dir(strPath)
While strfile <> ""
R = ThisWorkbook.Sheets("A").Range("A" & Rows.Count).End(xlUp).Row + 1
' Open the file and get the source sheet
Set wbSource = Workbooks.Open(strPath & strfile)
'Copy the data
RngInt = wbSource.Sheets("Int").Range("D5:D26")
RngExt = wbSource.Sheets("Ext").Range("D5:D26")
ReDim Arr(1 To 2, 1 To 28)
Arr(1, 1) = wbSource.Name
If RngInt(1, 1) = 0 Then
Arr(1, 2) = RngInt(2, 1)
Else
Arr(1, 2) = RngInt(1, 1)
End If
Arr(1, 3) = RngInt(4, 1)
Arr(1, 4) = RngInt(5, 1)
Arr(1, 5) = RngInt(6, 1)
Arr(1, 6) = RngInt(7, 1)
Arr(1, 7) = RngInt(17, 1) * (-1)
If RngExt(1, 1) = 0 Then
Arr(1, 8) = RngExt(2, 1)
Else
Arr(1, 8) = RngExt(1, 1)
End If
Arr(1, 9) = RngExt(4, 1)
Arr(1, 10) = RngExt(5, 1)
Arr(1, 11) = RngExt(6, 1)
Arr(1, 12) = RngExt(7, 1)
Arr(1, 13) = RngExt(17, 1) * (-1)
Arr(1, 14) = RngInt(2, 1) - Sheets("A").Range("N" & R)
Arr(1, 15) = RngInt(3, 1) - Sheets("A").Range("O" & R)
'And so on, until arr (1,27)
ThisWorkbook.Sheets("A").Range("A" & R).Resize(1, 28) = Arr
'Close the workbook and move to the next file.
wbSource.Close
strfile = Dir$()
Wend
End If
结束子
尝试,
Arr(1, 14) = RngInt(2, 1) - ThisWorkbook.Sheets("A").Range("N" & R)
Arr(1, 15) = RngInt(3, 1) - ThisWorkbook.Sheets("A").Range("O" & R)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.