VBA的新手,我仍在收集尽可能多的知识(并不断向前发展,但我受困了。
因此,基本上,我有一个名为“ Data”(数据库)的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
全部谢谢。
这应该让您开始使用
其背后的想法是,将表单的信息存储在变量中,然后查找工作表的数据并进行更新。
阅读代码的注释并根据需要进行调整
代码:
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
让我知道是否可行