excel 如何在FormulaR1C1 VBA中包含动态VLOOKUP?

ltqd579y  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(147)

我需要在另一个工作表上查找值。当我手动使用公式时,它工作得很好

=VLOOKUP(TRIM(C2),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)

但是,我需要能够使用VBA动态地将此公式插入到单元格中。这是我尝试的:

Set lookupRange = ThisWorkbook.Sheets("MyDataSheet").Range("A1:E500")
 Set newCol = tbl.ListColumns.Add
 newCol.DataBodyRange.FormulaR1C1 = "=VLOOKUP(TRIM(RC[-16])," & lookupRange.Address(True, True, xlR1C1) & ", 4, FALSE)"

这在Excel中插入公式,就像这样,但完全忽略了不同的工作表,并忽略了第二个TRIM:

=VLOOKUP(TRIM(C2),$A$1:$E$500),4,FALSE)

如何编写VBA动态插入VLOOKUP如下:=VLOOKUP(TRIM(C2),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)

bxgwgixi

bxgwgixi1#

你可以这样做:

Sub Tester()
    
    Dim tbl As ListObject, newCol As ListColumn, c As Range
    
    Set tbl = ActiveSheet.ListObjects(1) 'for example
    Set newCol = tbl.ListColumns.Add
    newCol.Name = "Lookup"

    ' "id" is the column with the values you want to look up
    Set c = tbl.ListColumns("id").DataBodyRange.Cells(1) 
    
    newCol.DataBodyRange.Formula2 = _
         "=VLOOKUP(TRIM(" & c.Address(False, False) & "),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)"
    
End Sub

相关问题