【发布时间】:2020-03-13 20:45:15
【问题描述】:
我正在使用本教程 (https://www.excel-easy.com/vba/examples/interactive-userform.html) 来了解如何创建一个交互式用户表单,该用户表单基于一个简单条件覆盖值,如果 ID 存在,则更新或编辑行。
但是,这对 TextBox 非常有效,但我正在努力从工具箱中添加其他控件。目前,我正在尝试在循环中添加 ComboBox,以便它可以从 ComboBox 添加值。
Private Sub ComboBox1_Change()
End Sub
Private Sub CommandButton1_Click()
EditAdd
End Sub
Private Sub CommandButton2_Click()
ClearForm
End Sub
Private Sub CommandButton3_Click()
Unload Me
End Sub
Private Sub TextBox1_Change()
GetData
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_Initialize()
TextBox1.SetFocus
ComboBox1.AddItem "One"
ComboBox1.AddItem "Two"
ComboBox1.AddItem "Three"
ComboBox1.AddItem "Four"
ComboBox1.AddItem "Five"
End Sub
这是模块。我试图通过在for 循环中添加UserForm.Controls("ComboBox" & j).Value = Cells(i + 1, j).Value 来修改它,但我只得到错误。
Dim id As Integer, i As Integer, j As Integer, flag As Boolean
Sub GetData()
If IsNumeric(UserForm.TextBox1.Value) Then
flag = False
i = 0
id = UserForm.TextBox1.Value
Do While Cells(i + 1, 1).Value <> ""
If Cells(i + 1, 1).Value = id Then
flag = True
For j = 2 To 6
UserForm.Controls("TextBox" & j).Value = Cells(i + 1, j).Value
UserForm.Controls("ComboBox" & j).Value = Cells(i + 1, j).Value
Next j
End If
i = i + 1
Loop
If flag = False Then
For j = 2 To 6
UserForm.Controls("TextBox" & j).Value = ""
UserForm.Controls("ComboBox" & j).Value = ""
Next j
End If
Else
ClearForm
End If
End Sub
Sub ClearForm()
For j = 1 To 6
UserForm.Controls("TextBox" & j).Value = ""
UserForm.Controls("ComboBox" & j).Value = ""
Next j
End Sub
Sub EditAdd()
Dim emptyRow As Long
If UserForm.TextBox1.Value <> "" Then
flag = False
i = 0
id = UserForm.TextBox1.Value
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
Do While Cells(i + 1, 1).Value <> ""
If Cells(i + 1, 1).Value = id Then
flag = True
For j = 2 To 6
Cells(i + 1, j).Value = UserForm.Controls("TextBox" & j).Value
Cells(i + 1, j).Value = UserForm.Controls("ComboBox" & j).Value
Next j
End If
i = i + 1
Loop
If flag = False Then
For j = 1 To 6
Cells(emptyRow, j).Value = UserForm.Controls("TextBox" & j).Value
Cells(emptyRow, j).Value = UserForm.Controls("ComboBox" & j).Value
Next j
End If
End If
End Sub
如果 ID 存在,如何将 ComboBox 添加到我的模块中,以便用户窗体覆盖现有值?
【问题讨论】:
-
什么错误?您的代码不包含对组合框的任何引用。你有组合框 2-5 吗?
-
@SJR 我刚刚更新了代码。我收到错误
Could not find the specified object. -
我认为这个错误是不言自明的,不是吗?检查组合框的名称,您的帖子只涉及一个。
-
我是 VBA 新手。我的用户表单中只有一个 ComboBox,我不明白为什么我需要组合框 2-5?
-
UserForm.Controls("ComboBox" & j)-j从 2 运行到 6,因此您需要将该行从循环中取出,只需参考 combobox1。我不完全确定你在做什么,但看起来你需要为 CB 复制文本框检查。
标签: excel vba loops combobox userform