我正在研究这个程序,你可以填写你需要多少表面和你想要的颜色,然后你得到颜色的配方。但是我对组合框有一个小问题就是选择颜色而我似乎无法修复它,有人可以帮助我。这是我制作的代码(我对vba很新)
Dim X As Integer
Dim A As Integer
Dim B As Integer
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "Colour1"
.AddItem "Colour2"
.AddItem "Colour3"
End With
End Sub
Private Sub CommandButton1_Click()
X = TextBox1.Text
Range("B2") = X
Range("B9").Value = A
Range("B10").Value = B
End Sub
Private Sub ComboBox_Change()
If ComboBox1.Text = "Colour1" Then
A = 3 And B = 5
ElseIf ComboBox1.Text = "Colour2" Then
A = 7 And B = 6
ElseIf ComboBox1.Text = "Colour3" Then
A = 4 And B = 8
End If
End Sub
由于某种原因,这部分是我使if语句不起作用。
答案 0 :(得分:0)
我看到的一些事情。
您的ComboBox_Change
需要ComboBox1_Change
,因此您没有引用正确的ComboBox
。
您正在为string
变量分配Integer
。你应该Dim X as String
。
如果您希望A
和B
变量在该模块的所有Subs中可用,则需要使用Public A and Integer
。否则,A
和B
中将没有值。
您还需要引用Sheet
和Range("B9")
中的Range("B10")
。因此,如果它位于 sheet1 ,那么ThisWorkBook.Sheets("sheet1").Range("B9")
。
见下面的修订代码:
Option Explicit
Public X As String
Public A As Long
Public B As Long
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "Colour1"
.AddItem "Colour2"
.AddItem "Colour3"
End With
End Sub
Private Sub CommandButton1_Click()
X = TextBox1.Text
Range("B2") = X
Sheet1.Range("B9").Value = A
Sheet1.Range("B10").Value = B
End Sub
' added the 1 to make it ComboBox1 which is the correct reference
Private Sub ComboBox1_Change()
If ComboBox1.Text = "Colour1" Then
'You can use And when assigning Variables values
'You need to do it seperately.
A = 3
B = 5
ElseIf ComboBox1.Text = "Colour2" Then
A = 7
B = 6
ElseIf ComboBox1.Text = "Colour3" Then
A = 4
B = 8
End If
End Sub