我在运行代码时遇到此错误,我不确定在哪里查看。
错误消息读取:运行时错误'1004' - 无法获取WorksheetFunction类的Vlookup属性
这是我的代码,varMajor在另一个工作表中被声明为全局变量。任何帮助将不胜感激!
Private Sub cmdRank_Click()
Dim strMajorRank As String
'Declare worksheet as an object variable
Dim shtRankings As Worksheet
'Set the variable
Set shtRankings = Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings")
varMajor = InputBox("Please Enter Your Major", "Where Does Your Major Rank?", vbOKOnly)
'Set rngMajorRank = Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings").Range("H2")
'Check to see if the major entered is listed in the Majors column in the data on the Rankings Worksheet using VLookup
If varMajor = "Finance" Then
strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
MsgBox "Your major is among the 20 most popular at CU!"
ElseIf varMajor = "Management" Then
strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
MsgBox "Your major is among the 20 most popular at CU!"
ElseIf varMajor = "Marketing" Then
strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
MsgBox "Your major is among the 20 most popular at CU!"
Else
MsgBox "Your major is still a good one to have!"
End If
'Go to worksheet with top 20 majors at CU Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings").Activate
shtRankings.Range("H2").Value = "strMajorRank"
End Sub
答案 0 :(得分:0)
所以看起来你的语法是正确的,这个错误实际上只是意味着Vlookup没有返回一个值,即在Excel中这个Vlookup将返回N / A#,你可以通过错误处理来处理它。如果公式是正确的,你想在你的Vlookup使用周围放置“On Error Resume Next”和“On Error Goto 0”。
您的代码有点不清楚,假设您正在尝试确定用户输入的值是否在您所说的列表中,那么它应该是:
'Check to see if the major entered is listed in the...
On Error Resume Next 'Goes to next line of code on error
strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
On Error Goto 0 'Returns error handling to default
If strMajorRank <> "" Then
MsgBox "Your major is among the 20 most popular at CU!"
Else
MsgBox "Your major is still a good one to have!"
End If
...