2017-11-11 87 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返回錯誤的可能性。