2016-10-18 58 views
0

我一直試圖將一個vlookup的結果分配給一個變量,但vlookup值實際上是一個用戶輸入,但不工作。InputData1變量沒有采用vlookup函數

我不知道我可以改變些什麼我的VBA代碼:(

它顯示我的VLOOKUP公式

 Sub Info() 

Dim the_sheet As Worksheet 
Dim table_list_object As ListObject 
Dim table_object_row As ListRow 
Dim inputData, inputData1 As String 
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction 
Dim rngLook As Range 

Set rngLook = Sheets("AutoZeroDatabase").Range("H1:I12") 

Set the_sheet = Sheets("Info") 
Set table_list_object = the_sheet.ListObjects("Table1") 
Set table_object_row = table_list_object.ListRows.Add 

inputData = InputBox("Enter a number from 1 to 12 to select a month i.e. 1 for January", "Input Box Text") 

inputData1 = wsFunc.VLookup(CInt(inputData), rngLook, 2, False) 

table_object_row.Range(1, 1).Value = inputData1 

MsgBox ("Thank you for taking the time to update me :)") 

End Sub 
+1

假設您在單元格H1:H12中有數字,請確保使用'wsFunc.VLookup(CInt(inputData),rngLook,2,False)'將'inputData'從'Variant'轉換爲Integer。 – YowE3K

+1

或者使用一個Application.InputBox而不是一個InputBox,並使用值爲1的'Type'參數。 – YowE3K

+0

你是男人:)。是的,該範圍的信息在第一列有數字,第二列有文字。我相信如果將變量更改爲整數,這可以被修復嗎? – Sam

回答

2

你的問題似乎出現,因爲你獲得調試錯誤從的InputBox一個字符串值,但然後比較這對數值在細胞H1:H12

我建議如下修改代碼:

Sub Info() 

    Dim the_sheet As Worksheet 
    Dim table_list_object As ListObject 
    Dim table_object_row As ListRow 
    Dim inputData 
    Dim inputData1 
    Dim rngLook As Range 

    Set rngLook = Sheets("AutoZeroDatabase").Range("H1:I12") 

    Set the_sheet = Sheets("Info") 
    Set table_list_object = the_sheet.ListObjects("Table1") 
    Set table_object_row = table_list_object.ListRows.Add 

    Do 
     inputData = Application.InputBox(Prompt:="Enter a number from 1 to 12 to select a month i.e. 1 for January", _ 
             Title:="Input Box Text", _ 
             Type:=1 + 4) 'Type 1 is number, 4 is boolean 
     If TypeName(inputData) = "Boolean" Then 
      If Not inputData Then 
       inputData1 = "User refused to supply the month!!" 
       Exit Do 
      End If 
     ElseIf inputData <> Int(inputData) Then 
      MsgBox "Fractions of a month are not allowed!" 
     ElseIf inputData < 1 Or inputData > 12 Then 
      MsgBox "Months are numbered 1 to 12 - what am I meant to do with " & inputData & "?!?!?" 
     Else 
      inputData1 = Application.VLookup(inputData, rngLook, 2, False) 
      If IsError(inputData1) Then 
       MsgBox "Something went very, very wrong - I couldn't find that value in the set of valid months!" 
      End If 
      Exit Do 
     End If 
    Loop 

    table_object_row.Range(1, 1).Value = inputData1 

    MsgBox ("Thank you for taking the time to update me :)") 

End Sub 
+1

上的代碼,而不是'WorksheetFunction.Vlookup'而不是'Application.Vlookup'。後者不允許返回錯誤值,並且如果在'rngLook'中找不到'inputData'值,你可能*需要捕獲錯誤值。您的驗證可以充分控制事物的用戶輸入端,但仍然有可能工作表本身被破壞或操作,這會在賦給inputData1時產生錯誤。 –

+0

感謝大家,我也想出我得到一個錯誤,因爲範圍更改爲1用戶添加了一列,但知道我得到它:) – Sam

+1

我更新了基於@DavidZemens建議的答案。 (我希望MSDN列出的VLookup作爲應用程序對象的方法之一!!) – YowE3K