就上下文而言,我正在建立一个用户及其爱好数据库。用户通过输入用户名通过UserForm1输入数据,然后勾选代表不同爱好的大量复选框。提交后,这将保存到工作表中,每个用户都作为一行(名称为字符串,复选框为true / false值),并为该用户分配一个ID号。
在UserForm2中,用户输入其ID号以返回其记录,以便他们可以更新自己的数据。我想添加一个按ID号搜索其记录的宏,然后返回UserForm1 并勾选/取消选中对应于yes / no值的复选框(例如相反的第一个宏)。然后,用户应该可以勾选/取消勾选框以更新其记录,并保存其旧数据。
这是UserForm1的代码(用户将数据输入到工作表中):
Private Sub saveAndCloseCommandButton_Click()
'When user clicks Save & Quit, save record as row
Dim lRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet3")
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
With ws
.Cells(lRow, 1).Value = nameTextBox.Value
.Cells(lRow, 2).Value = deptTextBox.Value
.Cells(lRow, 3).Value = notesTextBox.Value
'.Cells(1Row, 4) contains ID so do not write data to this column
'Give ID number to the user via MsgBox.
MsgBox "Saved. Your Skills Database ID is " & .Cells(lRow, 4) & ". Remember this!", VBA.VbMsgBoxStyle.vbOKOnly
'Populate the spreadsheet based on which skills the user selected, as TRUE (checkbox ticked) or FALSE (unticked).
.Cells(lRow, 5).Value = CheckBox1.Value
.Cells(lRow, 6).Value = CheckBox2.Value
...and so on, until
.Cells(lRow, 151).Value = CheckBox148.Value
End With
Call resetForm
'Close the form after saving
Unload Me
End If
End If
End Sub
'This is all the stuff that happens when the form resets (called above).
'The checkboxes should auto-untick.
Private Sub resetForm()
'Set all text boxes to blank
nameTextBox.Value = ""
deptTextBox.Value = ""
notesTextBox.Value = ""
'Set Focus on the Name text box
UserForm1.nameTextBox.SetFocus
End Sub