用于更新电子表格数据的命令框

时间:2016-10-19 12:32:06

标签: excel-vba vba excel

美好的一天,我在excel上使用组合框和命令按钮创建了一个userform,命令按钮用于根据组合框中选择的项目和带有数据的文本框更新电子表格上的数据,问题是每一个时间我单击命令按钮它不会更新数据,而是转到下一列并填写它。我希望在所选项目上更新数据

这是我试过的

  Private Sub CommandButton6_Click()
    Dim lrCD As Long
    lrCD = Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Cells(lrCD + 1, "A").Value = ComboBox1.Text
    Sheets("Sheet2").Cells(lrCD + 1, "B").Value = TextBox5.Text

1 个答案:

答案 0 :(得分:0)

按以下方式创建表单:

enter image description here

Sheet2中的A列包含将出现在组合框中的唯一值。

此代码位于表单中 打开表单时会触发UserForm_Initialize()事件,并使用值填充组合框 CommandButton6_Click事件会在A列中搜索,并将文本放在textbox5中所选值旁边。

Private Sub UserForm_Initialize()
    Dim lrCD As Long
    'Populate ComboBox with values from column A on Sheet2.
    With ThisWorkbook.Worksheets("Sheet2")
        lrCD = .Range("A" & Rows.Count).End(xlUp).Row
        Me.ComboBox1.RowSource = "'Sheet2'!" & .Range(.Cells(1, 1), .Cells(lrCD, 1)).Address
    End With
End Sub

Private Sub CommandButton6_Click()
    Dim rCell As Range
    With ThisWorkbook.Worksheets("Sheet2")

        'Look for the selected value in column A.
        Set rCell = .Columns(1).Find( _
            What:=Me.ComboBox1.Value, _
            After:=.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole)

        'If a value is found place the textbox value in the column next to it.
        If Not rCell Is Nothing Then
            rCell.Offset(, 1) = Me.TextBox5.Value
        End If
    End With

End Sub  

enter image description here