【问题标题】:Select a cell depending on value from UF Combobox根据 UF Combobox 中的值选择一个单元格
【发布时间】:2020-03-09 23:28:55
【问题描述】:

VBA 新手,我仍在尽可能多地收集知识(并继续前进),但我被困住了。

所以基本上我有一个名为“数据”(一个数据库)的 Excel 表,其中我在第一行的列上有客户名称,每个数据下都有一系列数据(年龄、性别、身高等)。

另一方面,我有一个用于更新数据的“Userform1”,每个信息都在一个 TextBox 中,用于您从“ComboBox2”中选择的客户端名称。 (您不能删除或添加客户端)。

我的目标是:填写表格后,我希望我的代码找到客户端单元格(从组合框中),然后通过将一个单元格偏移到下方并再次覆盖并再次覆盖来存储关联的数据。

(我可能不清楚,但 EN 不是我的母语,VBA 也不是)。

我的代码尝试:

Private Sub Target_click() 'Target Button is the button used to update data

    With ComboBox2
    Worksheets("Data").Activate
    ActiveSheet.Range (ComboBox2.Value)
    ActiveCell.Offset(1, 0).Value = TextBox1.Value.Activate 'TBox1 = Age
    ActiveCell.Offset(1, 0).Value = TextBox2.Value.Activate 'TBox2 = Sex
    ActiveCell.Offset(1, 0).Value = TextBox3.Value.Activate 'TBox3 = Height
    ... Etc ...
    End With

End Sub

谢谢。

【问题讨论】:

    标签: excel vba combobox userform


    【解决方案1】:

    这应该让你开始

    这背后的想法是将表单的信息存储在变量中,然后查找工作表的数据并更新它。

    阅读代码的 cmets 并根据您的需要进行调整

    代码:

    Private Sub Target_Click()
    
        Dim targetSheet As Worksheet
        Dim searchRange As Range
        Dim resultRange As Range
    
        Dim clientName As String
        Dim clientAge As Variant ' use long if you have validated the textbox to be numeric
        Dim clientSex As String
        Dim clientHeight As Variant ' use long if you have validated the textbox to be numeric
    
        Dim lastRow As Long
    
        ' Gather forms data
        clientName = Me.ComboBox1.Value
        clientAge = Me.TextBox1.Value
        clientSex = Me.TextBox2.Value
        clientHeight = Me.TextBox3.Value
    
        Set targetSheet = ThisWorkbook.Worksheets("Data")
    
        lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
    
        Set searchRange = targetSheet.Range("A1:G" & lastRow)
    
        ' Find the client
        Set resultRange = searchRange.Columns("A").Find(clientName)
    
        ' Exit if didn't find anything
        If resultRange Is Nothing Then Exit Sub
    
        ' If found, update cells
        With resultRange
            .Cells(1, "B").Value = clientAge
            .Cells(1, "C").Value = clientSex
            .Cells(1, "D").Value = clientHeight
        End With
    
    End Sub
    

    让我知道它是否有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多