如何在单击时将VLookUp代码添加到命令按钮

时间:2020-02-06 17:17:06

标签: excel vba

我有一个用户表单,可以根据用户输入将数据输入Excel。单击“确定”命令按钮后,将输入数据,表格将清除并移至下一个空行。在通过命令单击输入数据之前,我想验证带有弹出确认的文本输入-“员工ID ####是Bob Smith”-如果正确,则用户可以选择“确定”,并且数据输入代码将继续,如果没有,它将返回到用户表格进行更正。我尝试使用vlookup代码,但出现运行时或堆栈溢出错误。

这是我的代码:

Private Sub OkButton1_Click()

Dim myLookupValue As String
Dim myFirstColumn As Long
Dim myLastColumn As Long
Dim myColumnIndex As Long
Dim myFirstRow As Long
Dim myLastRow As Long
Dim myVLookupResult As Long

Dim myTableArray As Range

myLookupValue = IDTextBox
myFirstColumn = 1
myLastColumn = 2
myColumnIndex = 2
myFirstRow = 2
myLastRow = 500

    With Worksheets("Sheet2")
        Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn))
    End With

    myVLookupResult = WorksheetFunction.VLookup(myLookupValue, myTableArray, myColumnIndex, False)

    MsgBox "Employee Id" & myLookupValue & " is " & myVLookupResult
        Cancel = True

If Ok Then

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Dim x As Integer

    x = 0

    For Each cCont In Me.Controls
        If TypeName(cCont) = "CheckBox" Then
            If cCont.Value = True Then
                x = x + 1
            End If
        End If
    Next

    If x = 0 Then
        MsgBox "Please Select a Lunch Option"
        Else
        Cells(emptyRow, 1).Value = IDTextBox.Value
        End If

If MealCheckBox1.Value = True Then Cells(emptyRow, 2).Value = 5

If ExtraCheckBox2.Value = True Then Cells(emptyRow, 3).Value = 1

If DessertCheckBox3.Value = True Then Cells(emptyRow, 4).Value = 1

If DrinkCheckBox4.Value = True Then Cells(emptyRow, 5).Value = 1

Call Lunch_Initialize

IDTextBox.SetFocus

End If

End Sub

按原样使用代码,我收到运行时错误“ 1004”。无法获取WorksheetFunction类的VLookup属性。

0 个答案:

没有答案