VBA Excel Userform错误1004

时间:2017-03-01 02:43:18

标签: excel vba excel-vba combobox

我正在创建用户表单来更新公司数据。我的表单中的第一个控件是一个组合框(代码),其余的是文本框。现在我需要使用vlookup查找我的第一个控件,文本框的其余部分将使用我在组合框中键入的代码自动更新。但系统显示错误1004.有人可以帮我这个吗?以下是我的组合框代码:

Private Sub ComboBox_code_AfterUpdate()
    'check if value exist
    If WorksheetFunction.CountIf(Sheet1.Range("A:A"), Me.ComboBox_code.Value) = 0 Then
        MsgBox "Incorrect Code"
        Me.ComboBox_code.Value = ""
        Exit Sub

    End If
'lookup value based on first combobox
    With Me
        .TextBox_outlet = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 2, 0)
        .TextBox_invoice = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 3, 0)
        .TextBox_sales = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 4, 0)
        .TextBox_comm = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 5, 0)
        .TextBox_gst = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 6, 0)
        .TextBox_netsales = Application.WorksheetFunction.VLookup((Me.ComboBox_code), Sheet1.Range("Code"), 7, 0)
    End With
End Sub 

2 个答案:

答案 0 :(得分:0)

WAKE_LOCK提供所选索引,但您可以使用.List(.ListIndex)

获取所选项目
ComboBox.Value

答案 1 :(得分:0)

您还应该测试用户做出的任何实际组合框值选择

Select Case块可能是合适的:

Private Sub ComboBox_code_AfterUpdate()
    Dim codeRow As Long
    Dim codeRng As Range

    Set codeRng = Sheet1.Range("Code")
    With Me
        Select Case True

            'check if user selected a value
            Case .ComboBox_code.ListIndex = -1
                MsgBox "No Code selected!", vbCritical
                .ComboBox_code.Value = ""

            'check if value exist
            Case WorksheetFunction.CountIf(codeRng.Resize(, 1), .ComboBox_code.Value) = 0
                MsgBox "Incorrect Code", vbCritical
                .ComboBox_code.Value = ""

            Case Else
                codeRow = WorksheetFunction.Match(.ComboBox_code.Value, Sheet1.Range("Code"), 0) 'lookup value based on first combobox
                .TextBox_outlet = codeRng.cells(codeRow, 2)
                .TextBox_invoice = codeRng.cells(codeRow, 3)
                .TextBox_sales = codeRng.cells(codeRow, 4)
                .TextBox_comm = codeRng.cells(codeRow, 5)
                .TextBox_gst = codeRng.cells(codeRow, 6)
                .TextBox_netsales = codeRng.cells(codeRow, 7)
        End Select
    End With
End Sub

最后,您可能还想使用ComboBox_code_Change()事件处理程序而不是ComboBox_code_AfterUpdate():前者会在每个组合框更改(即选择)时触发,而后者仅在组合框无效时触发活动控件越长,即必须等待用户离开控件