使用组合框和Vlookup

时间:2017-10-09 19:06:15

标签: excel vba combobox textbox userform

我尝试用组合框制作我的第一个UserForm,我已经做了这个:

   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

所以我想从组合框中选择一个名字。在我选择了一个名字之后,我想在一个文本框中键入一个数字,这个数字将属于所选名称,并与现有数字相加。

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

谢谢

1 个答案:

答案 0 :(得分:0)

以下代码应该按照您的要求运作

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

用法

工作表名称替换为名称所在的工作表名称。

将名称的范围替换为我们可以找到工作表中所有名称的范围。

YourComboBox YourTextBoxValue 替换为userForm中组件的名称。