Excel VBA 带有组合框和 Vlookup 的用户表单

Excel VBA Userform with combo box and Vlookup

我尝试制作我的第一个带有组合框的用户窗体,我已经制作了这个:

   Private Sub cmdClose_Click()
   Unload Me
   End Sub

  Private Sub Reg1_AfterUpdate()
  If WorksheetFunction.CountIf(Stock.Range("A:A"), Me.Range.Value) = 0 Then
  NsgBox "This is an incorrect item"
  Me.Reg1.Value = ""
  Exit Sub
  End If

  With Me
  .Reg2 = Application.WorksheetFunction.VLookup(CLng(Me.Reg1), 
  Stock.Range("Lookup"), 2, 0)
  End Sub 

  Private Sub UserForm_Click()
  End Sub

问题是我不知道如何使用带有 Vlookup 功能的组合框。

我需要一个组合框,因为我想更改 Sheet1 上的数字。

例如:

       Harry      10
       David      20

  A1 Harry   B1  10
  A2 David   B2  20

所以我想 select 从组合框中取一个名字。在我 select 编辑了一个名字后,我想在文本框中输入一个数字,这个数字将属于 select 编辑的名字,并与现有数字相加。

所以 Harry 有 10 个。在我从组合框中 selected Harry 并在 TextBox 中设置 90 之后,Harry 的数字将变为 100。这就是为什么我认为我必须在 VBA 中以某种方式使用 Vlookup。

谢谢

下面的代码应该可以按照您的要求工作

Sub ChangeValue()
    Dim sheetName As String

    sheetName = "Name of your sheet"

    With ThisWorkbook.Sheets(sheetName)
       'For each name in your range
        For Each cell In .Range("Your range where names are") 
           'If the name is the one selected in your combobox
            If (cell = YourComboBox.Text) Then
                'Increment value 
                .Range(cell.Address).Offset(0, 1).Value = _
                .Range(cell.Address).Offset(0, 1).Value + YourTextBoxValue.Text
            End If
        Next cell
    End With
End Sub

用法

将您的 sheet 的 名称替换为名称所在 sheet 的名称。

你的名字范围替换为我们可以在你的sheet中找到所有名字的范围。

YourComboBoxYourTextBoxValue 替换为用户窗体中组件的名称。