我试图学习VBA excel。
我有两个标签:Sheet1和Sheet2:
在Sheet1中,我有从A1到D6的数据。我决定把这个范围变成一个名字" iJob"。 (='工作表Sheet' $ A $ 2:$ d $ 6)
在Sheet2中,我想要在Sheet1中检查数据。
当我把它放在像B2这样的细胞上时 " = VLOOKUP(A2,iJob,4,0)" - 它有效,我可以从Sheet1检查我需要的值。
我想将其纳入VBA,这是我的代码:
Dim Tab2 As String
Dim txt As String
With ActiveSheet
txt = Range("A2").Value
Tab2 = Range("A2").Formula ="=VLOOKUP(txt,iJob,4,0)"
End With
MsgBox Tab2
我的结果是" False"而不是我在单元格中使用时得到的那个
编辑:更正了一些参考
答案 0 :(得分:2)
比您预期的要容易:
Dim Tab2 As String
Dim txt As String
With ActiveSheet
txt = .Range("A2").Value
.Range("A2").Formula ="=VLOOKUP(" & txt & ",iJob,4,0)"
Tab2 = .Range("A2").Value
MsgBox Tab2
' or
MsgBox .Range("A2").Value
End With
或者:
txt = Evaluate("VLOOKUP(""" & txt & """, iJob, 4, 0)")
MsgBox txt
Oneliner:
MsgBox Evaluate("VLOOKUP(""" & txt & """, iJob, 4, 0)")
另一种方法:
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
MsgBox wsFunc.VLookup(txt, Worksheets("Sheet1").Range("iJob"), 4, False)
虽然WorksheetFunctions通常很慢。
答案 1 :(得分:1)
尝试 -
Range("B2").Formula = "=VLOOKUP(A2,Sheet1!$A$2:$D$6,4,0)"
Tab2 = Range("B2").Value
你也可能会参与这个问题 - How to use a VLOOKUP function in Excel VBA
纯粹使用VBA
Sub foo()
Dim wb As Workbook
Dim txt As String
Dim iJob As Range
Dim tab2 As String
Set wb = ThisWorkbook
Set iJob = wb.Worksheets("Sheet1").Range("A2:D6") ' the table ranage where to search
txt = wb.Worksheets("Sheet2").Range("A2").value ' the lookup value
On Error Resume Next
tab2 = Application.WorksheetFunction.VLookup(txt, iJob, 4, False)
MsgBox tab2 ' the search result
End Sub