VBA 基于另一个组合框的组合框选项
VBA combobox options based on another combobox
我有一个组合框,选项从 300 到 650,增量为 10,我需要另一个组合框来显示前一个值的选项 -5 和前一个值的 -15,所以如果第一个组合框选择是 300,那么另一个组合框显示选项 295 和 285。我知道可以手动写下所有情况的所有选项,但这太疯狂了。我想知道是否有人对此有简单的解决方案?
Private Sub UserForm_Initialize()
ComboBox1.AddItem "300"
ComboBox1.AddItem "310"
ComboBox1.AddItem "320"
End Sub
Private Sub ComboBox1_Change()
Application.EnableEvents = False
ComboBox2.Clear
Application.EnableEvents = True
Select Case ComboBox1.Value
Case "300"
ComboBox2.AddItem "295"
ComboBox2.AddItem "285"
End Select
End Sub
使用简单的数学:
Private Sub UserForm_Initialize()
Dim i As Long
ComboBox1.Clear
For i = 300 To 650 Step 10
ComboBox1.AddItem CStr(i)
Next
End Sub
Private Sub ComboBox1_Change()
Application.EnableEvents = False
ComboBox2.Clear
Application.EnableEvents = True
Dim cb1Val
cb1Val = val(ComboBox1.Value)
If cb1Val > 0 Then
ComboBox2.AddItem CStr(cb1Val - 5)
ComboBox2.AddItem CStr(cb1Val - 15)
End If
End Sub
填充组合框
- 为了将数据快速加载到组合框或列表框,它是 recommended to use the
List
属性 和一个值数组。
代码
Option Explicit
Private Sub UserForm_Initialize()
Const nMin As Long = 300
Const nMax As Long = 650
Const nInc As Long = 10
Dim n As Long: n = Int((nMax - nMin) / nInc)
Dim arr() As Long: ReDim arr(0 To Int((nMax - nMin) / nInc))
Dim nCurr As Long: nCurr = nMin
Dim i As Long
For i = 0 To n
arr(i) = nCurr
nCurr = nCurr + nInc
Next i
ComboBox1.List = arr
End Sub
Private Sub ComboBox1_Change()
With ComboBox2
.Clear
.AddItem ComboBox1.Value - 5
.AddItem ComboBox1.Value - 15
End With
End Sub
我有一个组合框,选项从 300 到 650,增量为 10,我需要另一个组合框来显示前一个值的选项 -5 和前一个值的 -15,所以如果第一个组合框选择是 300,那么另一个组合框显示选项 295 和 285。我知道可以手动写下所有情况的所有选项,但这太疯狂了。我想知道是否有人对此有简单的解决方案?
Private Sub UserForm_Initialize()
ComboBox1.AddItem "300"
ComboBox1.AddItem "310"
ComboBox1.AddItem "320"
End Sub
Private Sub ComboBox1_Change()
Application.EnableEvents = False
ComboBox2.Clear
Application.EnableEvents = True
Select Case ComboBox1.Value
Case "300"
ComboBox2.AddItem "295"
ComboBox2.AddItem "285"
End Select
End Sub
使用简单的数学:
Private Sub UserForm_Initialize()
Dim i As Long
ComboBox1.Clear
For i = 300 To 650 Step 10
ComboBox1.AddItem CStr(i)
Next
End Sub
Private Sub ComboBox1_Change()
Application.EnableEvents = False
ComboBox2.Clear
Application.EnableEvents = True
Dim cb1Val
cb1Val = val(ComboBox1.Value)
If cb1Val > 0 Then
ComboBox2.AddItem CStr(cb1Val - 5)
ComboBox2.AddItem CStr(cb1Val - 15)
End If
End Sub
填充组合框
- 为了将数据快速加载到组合框或列表框,它是 recommended to use the
List
属性 和一个值数组。
代码
Option Explicit
Private Sub UserForm_Initialize()
Const nMin As Long = 300
Const nMax As Long = 650
Const nInc As Long = 10
Dim n As Long: n = Int((nMax - nMin) / nInc)
Dim arr() As Long: ReDim arr(0 To Int((nMax - nMin) / nInc))
Dim nCurr As Long: nCurr = nMin
Dim i As Long
For i = 0 To n
arr(i) = nCurr
nCurr = nCurr + nInc
Next i
ComboBox1.List = arr
End Sub
Private Sub ComboBox1_Change()
With ComboBox2
.Clear
.AddItem ComboBox1.Value - 5
.AddItem ComboBox1.Value - 15
End With
End Sub