我有一个Excel VBA UserForm,我无法开始工作。第一个组合框需要链接到相关表(年份)。然后,第二个组合框或列表框将在所选工作表的第一列(月份)中获取数据,然后输入数据并显示在相关行的相关工作表中。 我的编码是基本的,我的引用是错误的,你能帮忙吗?
这是有效的,它将它放在正确的工作表中,但不在右边的行(组合框2)中:
Private Sub CommandButton1_Click()
With ThisWorkbook.Worksheets(cboTest.Value)
.Range("D2").Value = nightElec
.Range("F2").Value = dayHeat
.Range("G2").Value = nightHeat
.Range("I2").Value = dayWater
.Range("J2").Value = nightWater
dayElec = Empty
End With
End Sub
答案 0 :(得分:5)
如何将此作为用户表单的代码使用:
Private Sub UserForm_Initialize()
Dim wks As Worksheet
'loop through all worksheets
For Each wks In ThisWorkbook.Worksheets
'add their names as items to your combo-box
cboTest.AddItem wks.Name
Next wks
End Sub
然而,这只是其中一种方法。在这里,我假设您没有以任何其他形式保存工作表名称 - 例如数组 - 并且需要获取此信息。
此外,这只是用户表单初始化的例程 - 而不是更新。
Private Sub UserForm_Initialize()
InitCbo
End Sub
Private Sub InitCbo()
Dim wks As Worksheet
With cboTest
'delete all current items of cboTest
.Clear
'loop through all worksheets
For Each wks In ThisWorkbook.Worksheets
'add their names as items to your combo-box
.AddItem wks.Name
Next wks
'select first item
.ListIndex = 0
End With
End Sub
现在您可以使用InitCbo
更新组合框。就像点击按钮或添加新工作表一样。
您可能也对List
属性感兴趣,因为您也可以使用它设置项目 - 就像在这个excel-help示例中一样:
Dim MyArray(6,3)
Private Sub UserForm_Initialize()
Dim i As Single
'The 1-st list box contains 3 data columns
ListBox1.ColumnCount = 3
'The 2nd box contains 6 data columns
ListBox2.ColumnCount = 6
'Load integer values into first column of MyArray
For i = 0 To 5
MyArray(i, 0) = i
Next i
'Load columns 2 and three of MyArray
MyArray(0, 1) = "Zero"
MyArray(1, 1) = "One"
MyArray(2, 1) = "Two"
MyArray(3, 1) = "Three"
MyArray(4, 1) = "Four"
MyArray(5, 1) = "Five"
MyArray(0, 2) = "Zero"
MyArray(1, 2) = "Un ou Une"
MyArray(2, 2) = "Deux"
MyArray(3, 2) = "Trois"
MyArray(4, 2) = "Quatre"
MyArray(5, 2) = "Cinq"
'Load data into ListBox1 and ListBox2
ListBox1.List() = MyArray
ListBox2.Column() = MyArray
End Sub
我知道,这是一个ListBox的例子 - 但据我所知,它也适用于ComboBox或至少是simmilar。
编辑:
您粘贴的代码将始终使用活动工作簿和活动工作表,因此Range("C2").Value = dayElec
不会更改列表/组合框的选定工作表的值。
您需要将其修改为:
Private Sub CommandButton1_Click()
With ThisWorkbook.Worksheets(cboTest.value)
.Range("D2").Value = nightElec
.Range("F2").Value = dayHeat
.Range("G2").Value = nightHeat
.Range("I2").Value = dayWater
.Range("J2").Value = nightWater
dayElec = Empty
End With
End Sub