这是navrec的声明
Public navrec(1 To 100000, 100) As Variant
navrec(r,c) = Cells(r,c)
我在上面的for循环行中遇到下标超出范围错误的下标
我试图用VB-Excel的有限工作知识来修复这个宏。我假设前面的循环范围' navreclr
& navreclc
引用的数据区域太大了?
Sub import_navr()
EntityList = mywkb.Sheets("Source Files").Range("nrlist")
navreclr = 0
days = 0
fname = navrecloc
If Dir(fname) = "" Then
MsgBox ("Please save current PVAL. Macro will end")
End
End If
Workbooks.Open fname, ReadOnly:=True
Set tempbk = ActiveWorkbook
navreclr = Cells(1048576, 1).End(xlUp).Row
navreclc = Sheets(1).Cells(1, 1).End(xlToRight).Column
For r = 1 To navreclr
For c = 1 To navreclc
navrec(r, c) = Cells(r, c)
Next c
Next r
For c = 1 To navreclc
If navrec(1, c) = "ENTITY_ID" Then einr = c
If navrec(1, c) = "SHARE_CLASS" Then scnr = c
If navrec(1, c) = "LEDGER_ITEMS" Then linr = c
If navrec(1, c) = "BALANCE_CHANGE" Then bcnr = c
Next c
Set ofs = CreateObject("Scripting.FileSystemObject")
mywkb.Sheets("Source Files").Range("nrlist").Cells(1, 2) = ofs.GetFile(fname).Datelastmodified
tempbk.Close savechanges:=False
End Sub
答案 0 :(得分:0)
问题是您的数组navrec
的大小不正确,无法容纳所有单元格。您可以通过在循环上方直接添加以下代码来解决此问题(我已在下面添加了循环):
ReDim navrec(navreclr, navreclc) As Variant
For r = 1 To navreclr
For c = 1 To navreclc
navrec(r, c) = Cells(r, c)
Next c
Next r
当您动态确定数组的维数时,如本示例所示,通常最好动态声明数组,而不是使用常量。除非有充分理由这样做,否则尽量不要过度使用内存。
您还需要在全局模块中声明变量dimensionless,否则您将收到一条错误,指出“数组已经过尺寸标注。”
替换:
Public navrec(1 To 100000, 100) As Variant
与
Public navrec() As Variant
消除此错误。
答案 1 :(得分:0)
您可以直接在一个操作中获取矩形数组的值:
Set tempbk = Workbooks.Open(fname, ReadOnly:=True)
With tempbk.Sheets(1)
'get row/col counts
navreclr = .Cells(.Rows.Count, 1).End(xlUp).Row
navreclc = .Cells(1, .Columns.Count).End(xlToLeft).Column
'assign range value to array
nacrec = .cells(1).Resize(navreclr, navreclc).Value
End With