我一直在尝试将vlookup的结果分配给变量,但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
答案 0 :(得分: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