2017-11-11 422 views
1

我不知道我是否解释得很好。我是一名初学者,我试图在VBA中使用VLOOKUP从文件中获取一个值。然而,即使我可以明显地使用字符串本身,我也不能将它用作变量。如何在VBA中使用VLOOKUP中的变量作为范围评估?

因此,当我在下拉列表中选择某些内容时,其想法是自动填充两个文本框。 Dropwdown本身决定了包含数据的工作表。

Private Sub cbProductList1_Change() 
    vCode1 = Application.WorksheetFunction.VLookup(cbProductList1.Value, 
    [Products!A:B], 2, False) 
    Me.tbProdCode1 = vCode1 
    vPrice1 = Evaluate("VLOOKUP(" & vCode1 & ", " & Me.labelCFValue & ", 2, False)") 
    Me.tbPrice1 = vPrice1 
End Sub 

如果我在vCode1上运行MsgBox - 它给了我需要成为VLOOKUP的第一个参数的字符串。 如果我在Me.labelCFValue上运行MsgBox,它会给我CF_1!A25:B33(不带引号),就像我需要它一样。但是当我在vPrice1上运行MsgBox时,出现错误。

以后编辑:另外,如果你能帮我使用Me.labelCFValue里面Application.WorksheetFunction.VLookup(),这也可能是好的。

请帮忙?

+1

如果你创建一个用户定义的函数,你可以返回labelCFvalue的值(例如'Public Function getlabelCF()as string getlabelCF = Me.labelCFValue End Function') – serakfalcon

+0

谢谢!这解决了它! – NsD

回答

1

我无法测试代码,但相信这应该工作或帮助您找到自己的方式。

Option Explicit 

Private Sub cbProductList1_Change() 

    Dim Rl As Long        ' last row 
    Dim LookupRange As Range 
    Dim Sp() As String       ' splitting labelCFValue 
    Dim vCode1 As String 
    Dim vPrice1 As Double 

    ' ActiveSheet is the default, but better to declare 
    With ActiveSheet 
     Rl = .Cells(.Rows.Count, "A").End(xlUp).Row 
     Set LookupRange = .Range(.Cells(1, 1), Cells(Rl, 2)) 
    End With 
    vCode1 = Application.VLookup(cbProductList1.Value, LookupRange, 2, False) 
    Me.tbProdCode1 = vCode1 

    ' If Me.labelCFValue is a Label, the string should be its Caption property. 
    ' If it is a Textbox the string should be its Value or Text property. 
    ' Either way, it is better to specify what you are addressing:- 
    Sp = Split(Me.labelCFValue, "!") 
    Set LookupRange = Worksheets(Sp(0)).Range(Sp(1)) 
    vPrice1 = Evaluate(Application.VLookup(vCode1, LookupRange, 2, False)) 
    Me.tbPrice1 = vPrice1 
End Sub 

考虑添加一些预防性代码来处理任一Vlookups返回错误的可能性。