如何使用子过程中的变量为userForm中的comboBox添加特定项?
子程序(模块代码) -
Dim main As Integer
Public Sub dataValidation()
For i = 3 To 22
If Cells(i, 7).Value = "" Then
If Cells(i, 6).Value = "x" Then
main = 1
ElseIf Cells(i, 6).Value = "y" Then
main = 2
ElseIf Cells(i, 6).Value = "z" Then
main = 3
End If
form.Show
End If
Next
End Sub
表单初始化(表单代码) -
Private Sub UserForm_Initialize()
cboSubtype.Value = "Select subtype"
if main = 1 then
cboSubtype.AddItem "a"
cboSubtype.AddItem "s"
elseif main = 2 then
cboSubtype.AddItem "d"
cboSubtype.AddItem "f"
elseif main = 3 then
cboSubtype.AddItem "g"
cboSubtype.AddItem "h"
End Sub
答案 0 :(得分:2)
下面的代码使用您想要的方法,将变量main
从模块传递给User_Form init事件。
注意:您可以执行1个代码(在user_form init事件中)。
Sub dataValidation 代码(模块)
Option Explicit
Public main As Integer
Public Sub dataValidation()
Dim i As Integer
For i = 3 To 22
If Cells(i, 7).Value = "" Then
Select Case Cells(i, 6).Value
Case "s"
main = 1
Case "y"
main = 2
Case "z"
main = 3
End Select
form.Show
End If
Next i
End Sub
Sub User_Form 代码(在初始事件中)
Private Sub UserForm_Initialize()
With cboSubtype
.Value = "Select subtype"
Select Case main
Case 1
.AddItem "a"
.AddItem "s"
Case 2
.AddItem "d"
.AddItem "f"
Case 3
.AddItem "g"
.AddItem "h"
End Select
End With
End Sub
答案 1 :(得分:1)
Private Sub UserForm_Initialize()
this = "this": that = "that": thenext = "thenext"
With ComboBox1
.AddItem this
.AddItem that
.AddItem thenext
End With
End Sub
这为我编译。