簡體   English   中英

帶數組下標的VLOOKUP超出范圍

[英]VLOOKUP with Array Subscript out of range

我正在嘗試做我認為應該是一個簡單公式的操作,但是事實證明這很困難。 我試圖通過VBA將單元格設置為等於公式。 這是代碼:

Dim pivotws_month As Worksheet
Dim departmentArray() As Variant
Dim i As Long
Dim x As Long
Dim lrow As Long

lrow = pivotws_month.Cells(Rows.Count, 2).End(xlUp).Row
ReDim departmentArray(1 to lrow)
departmentArray = pivotws_month.Range("B4:B" & lrow)

i = 4  
For x = 1 to UBound(departmentArray)
   pivotws_month.Cells(i,4).Value = pivotws_month.Cells(i,3) / Application.WorksheetFunction.VLookup(departmentArray(x), pivotws_month.Range("G4:H" & lrow), 2, False)
i = i + 1
Next x

我已經調試了變量,並且貸款正確(297),數組中的項目數正確(294)。 我不斷在For循環中收到下標超出范圍的錯誤,我不確定為什么。 請幫助,我一直在尋找答案。

您已經創建了2D數組; 提供所有參考文獻中的排名。

...

'this Redim is completely unnecessary
'ReDim departmentArray(1 to lrow)

...

with pivotws_month
    i = 4  
    lrow = .Cells(Rows.Count, 2).End(xlUp).Row
    'create a 2-D array of many 'rows' and one 'column
    departmentArray = .Range("B4:B" & lrow).value
    For x = LBound(departmentArray, 1) to UBound(departmentArray, 1)
       .Cells(i,4).Value = .Cells(i,3) / Application.VLookup(departmentArray(x, 1), .Range("G4:H" & lrow), 2, False)
        i = i + 1
    Next x
end with

從工作表范圍加載變體數組始終會導致二維數組。 從單行還是單列加載都沒有關系。 它還會在批量加載代碼行之前將任何Option Base 0聲明或ReDim命令丟棄到一維數組。

您可以在批量加載事件之后使用以下方法測試陣列的尺寸。

debug.print lbound(departmentArray, 1) & ":" & ubound(departmentArray, 1)
debug.print lbound(departmentArray, 2) & ":" & ubound(departmentArray, 2)

將第一個等級(例如ubound(departmentArray, 1) )視為數組的“行”,將第二個等級(例如ubound(departmentArray, 2) )視為數組的“列”可能會有所幫助。

該VLOOKUP沒有錯誤控制。 一個簡單的不匹配#N / A將使您的代碼陷入混亂。 可以將Application.Vlookup的結果放入一個變量中,並且可以使用IsError測試該變量。 可以使用針對零變量的進一步測試來避免#DIV / 0! 代碼中除法運算的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM