如何将其用作用户表单的代码:
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
属性感兴趣,因为您也可以使用它设置 Items - 就像在这个 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 或至少类似。
编辑:
您粘贴的代码将始终使用活动工作簿和活动工作表,因此这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