VBA – 循环工作表将年份添加到combobox
我有20个工作表上的私人小combobox。 我试图在combobox中预加载一年的月份,但是我似乎无法使它工作。 我现在的代码有什么问题? 第一个combobox只增加了120个像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
发生这种情况是因为您使用ws
variables循环显示工作表,而对于每个工作表,您都要将当前月份添加到当前的ActiveSheet
。 你可以在第一个ActiveSheet.Combobox...
行之前做一个ws.Activate
,然而 – 这只是一个很坏的做法(参见如何避免select/激活
不好的例子:
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
variables,然后通过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