这可能听起来令人困惑,但我希望你能耐心听我说。我有一个用于数据输入的用户表单,其中有一个指定用于员工 ID 的文本框和指定用于其人口统计数据的各种组合框。是否可以创建一个 vba 代码,允许我在文本框中输入多个员工 ID,并且每个组合框回答的任何信息都将应用于所有员工 ID?
Private Sub CommandButton1_Click()
Dim sh As Worksheet, msg As String
'check for any empty required fields
If Len(TextBox1.Value) = 0 Then msg = msg & vbLf & " - Employee ID"
If Len(msg) > 0 Then 'anything missing?
MsgBox "The following fields are required:" & msg, _
vbOKOnly + vbCritical, "Missing Information"
Else
'OK to write to sheet
Set sh = ThisWorkbook.Sheets("Employee Information")
With sh.Cells(Rows.Count, "A").End(xlUp).Offset(1)
.Resize(1, 12).Value = Array(TextBox1.Value, ComboBox1.Value, _
ComboBox2.Value, ComboBox3.Value, ComboBox4.Value, _
ComboBox5.Value, ComboBox6.Value, ComboBox7.Value, _
ComboBox8.Value, ComboBox9.Value, ComboBox10.Value, _
ComboBox11.Value)
MsgBox "Employee Information Added", vbOKOnly + vbInformation, "ERROR"
Unload Me
End With
End If
End Sub
如果您输入多个以逗号分隔的 ID,您可以执行以下操作:
Private Sub CommandButton1_Click()
Dim sh As Worksheet, msg As String, arr, c As Range, id
'check for any empty required fields
If Len(TextBox1.Value) = 0 Then msg = msg & vbLf & " - Employee ID"
If Len(msg) > 0 Then 'anything missing?
MsgBox "The following fields are required:" & msg, _
vbOKOnly + vbCritical, "Missing Information"
Else
'OK to write to sheet
Set sh = ThisWorkbook.Sheets("Employee Information")
Set c = sh.Cells(Rows.Count, "A").End(xlUp).Offset(1) '##start adding here
arr = Split(TextBox1.Value, ",") '##split on comma to get an array
For Each id In arr '##loop over the array
c.Resize(1, 12).Value = Array(Trim(id), ComboBox1.Value, _
ComboBox2.Value, ComboBox3.Value, ComboBox4.Value, _
ComboBox5.Value, ComboBox6.Value, ComboBox7.Value, _
ComboBox8.Value, ComboBox9.Value, ComboBox10.Value, _
ComboBox11.Value)
Set c = c.Offset(1) '##next output row
Next id
MsgBox "Employee Information Added", vbOKOnly + vbInformation, "ERROR"
Unload Me
End If
End Sub