VBA - 循环通过工作表将年份添加到组合框中

时间:2017-07-03 18:31:45

标签: excel vba excel-vba combobox

我在20个工作表上有Private Sub组合框。我试图在组合框中预加载一年中的几个月,但我似乎无法使它工作。我目前的代码有什么问题?它只会在第一个组合框中添加12个月,120次:

Sub WorkBook_Open()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
        ActiveSheet.ComboBox1.AddItem "January"
        ActiveSheet.ComboBox1.AddItem "February"
        ActiveSheet.ComboBox1.AddItem "March"
        ActiveSheet.ComboBox1.AddItem "April"
        ActiveSheet.ComboBox1.AddItem "May"
        ActiveSheet.ComboBox1.AddItem "June"
        ActiveSheet.ComboBox1.AddItem "July"
        ActiveSheet.ComboBox1.AddItem "August"
        ActiveSheet.ComboBox1.AddItem "September"
        ActiveSheet.ComboBox1.AddItem "October"
        ActiveSheet.ComboBox1.AddItem "November"
        ActiveSheet.ComboBox1.AddItem "December"
Next ws
End Sub

1 个答案:

答案 0 :(得分:3)

这是因为您使用ws变量循环浏览工作表,但是对于每个工作表,您将月份添加到当前ActiveSheet。不过,您可以在第一行ws.Activate之前执行ActiveSheet.Combobox... - 这只是一种不好的做法(参见how to avoid Select / Activate

错误示例:

Sub WorkBook_Open()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
   ws.Activate
   ActiveSheet.ComboBox1.AddItem "January"
   ActiveSheet.ComboBox1.AddItem "February"
   '....
Next ws
End Sub

最好使用ws变量,然后通过OLEObjects集合访问控件。

好例子:

Option Explicit
Private Sub Workbook_Open()
Dim ws As Worksheet
Dim i As Integer

For Each ws In ThisWorkbook.Worksheets
    With ws.OLEObjects("Combobox1").Object
        For i = 1 To 12
            .AddItem Format(DateSerial(2017, i, 1), "mmmm") 'as per comment!
        Next i
    End With
Next ws
End Sub