[英]Issue with vlookup and absolute reference and lastrow VBA
我有一個宏,它通過在 J 列中獲取供應商名稱來執行 vlookup,並在 C 列和 D 列中我的 vlookup 的表數組中查找供應商編號。但是,當我運行宏時,我的 vlookup 出現了明顯的錯誤。 請參閱所附圖片中的公式。 顯然,我的 vlookup 中的表數組部分無法正常工作。 實際上,我希望我的 vlookup 從原點 C5 返回一個固定的表數組(我的意思是使用絕對引用和美元),並將 D 列中的最后一行作為限制點(我的意思是我的表數組的限制應該是D 列的最后一行)。
請看下面我的 VBA 代碼,我的 vlookup 中的這部分 VBA 代碼似乎是錯誤的:C4" & LastRow & "
非常感謝你的幫助。 哈維
Sub insertvlookuptogetmyvendornumber()
Dim LastRow As Integer
LastRow = Range("D" & Rows.Count).End(xlUp).Row
PenultimateLastRow = Range("J" & Rows.Count).End(xlUp).Offset(-1, 0).Row
Range("I4").Select
ActiveCell.FormulaR1C1 = "Vendor number"
Range("I5").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[1],R5C3:C4" & LastRow & ",2,0)"
Selection.AutoFill Destination:=Range("I5:I" & PenultimateLastRow), Type:=xlFillDefault
End Sub
根據我的評論,我將維護一個歷史名稱和數字表。 我最初會將其讀入字典,然后循環數據透視表的適當列,如果名稱存在,則更新字典值。 如果名稱不存在,則將名稱和編號添加到字典中。 最后將其全部寫回歷史表。
歷史表是您嘗試執行 VLookup 的當前表。 在這種情況下,該表將只包含從數據透視表添加新值或更新現有值的匹配對。
重申一下,右邊的表,I 和 J 列應該只在開始時有匹配的對。 硬編碼。
這假設數據透視表正文中沒有小計/總計行,盡管可以通過更新代碼排除這些行(如果存在)。
Option Explicit
Public Sub UpdateReferenceTable()
Dim lastRow As Long, dict As Object, ws As Worksheet, pvt As PivotTable, i As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set pvt = ws.PivotTables("PivotTable1")
Set dict = CreateObject("Scripting.Dictionary")
With ws
lastRow = .Cells(.Rows.Count, "I").End(xlUp).Row
End With
Dim initialDictData(), pivotTableUpdates()
initialDictData = ws.Range("I9:J" & lastRow).Value
For i = LBound(initialDictData, 1) To UBound(initialDictData, 1)
dict(initialDictData(i, 2)) = initialDictData(i, 1)
Next
Dim names(), vendorNumbers()
names = Application.Transpose(pvt.PivotFields("Name 1").DataRange.Value)
vendorNumbers = Application.Transpose(pvt.PivotFields("Vendor Number").DataRange.Value)
For i = LBound(names) To UBound(names)
If names(i) <> vbNullString Then
If dict.exists(names(i)) Then
dict(names(i)) = vendorNumbers(i)
Else
dict.Add names(i), vendorNumbers(i)
End If
End If
Next
ws.Range("I9").Resize(dict.Count, 1) = Application.Transpose(dict.items)
ws.Range("J9").Resize(dict.Count, 1) = Application.Transpose(dict.Keys)
End Sub
數據:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.