4

我正在编写 VBA 代码来用相同的数据填充三个不同的组合框。我只是想知道是否有比我现在正在做的更有效的编写方式?

' Create fac1 cbo
For Each c_fac In ws_misc.Range("fac")
    With Me.cbo_fac1
    .AddItem c_fac.Value
    .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
Next c_fac

' Create fac2 cbo
For Each c_fac In ws_misc.Range("fac")
    With Me.cbo_fac2
    .AddItem c_fac.Value
    .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
Next c_fac

' Create fac3 cbo
For Each c_fac In ws_misc.Range("fac")
    With Me.cbo_fac3
    .AddItem c_fac.Value
    .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
Next c_fac

感谢您抽出宝贵的时间!

4

4 回答 4

8

更进一步,可能:

dim lLoop as long
' Create fac1 cbo
For Each c_fac In ws_misc.Range("fac")
    For lLoop=1 to 3
        Me.controls("cbo_fac" & lLoop).AddItem c_fac.Value
        Me.controls("cbo_fac" & lLoop).List(Me.controls("cbo_fac" & lLoop).ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    next lLoop
Next c_fac
于 2012-10-10T22:32:25.867 回答
3

为什么你不能这样做?:

' Create fac1 cbo
For Each c_fac In ws_misc.Range("fac")
    With Me.cbo_fac1
        .AddItem c_fac.Value
        .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
    With Me.cbo_fac2
        .AddItem c_fac.Value
        .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
    With Me.cbo_fac3
        .AddItem c_fac.Value
        .List(.ListCount - 1, 1) = c_fac.Offset(0, 1).Value
    End With
Next c_fac

这将您在工作表范围内循环所需的时间减少了 2/3。通常读取和写入实际的 Excel 工作表对象是 Excel VBA 代码中花费最多时间的部分。

于 2012-10-10T22:25:05.323 回答
2

这会快得多(假设“fac”是一列),.AddItem 对于> 5个条目非常慢:

Dim rng
rng = ws_misc.Range("fac").resize(,2).value
Me.cbo_fac1.List = rng
Me.cbo_fac2.List = rng
Me.cbo_fac3.List = rng
于 2012-10-11T08:42:29.030 回答
1

我个人不喜欢With这种情况。它使代码行数翻了一番,几乎没有任何好处。你可以把它缩小到:

' Create fac1 cbo
For Each c_fac In ws_misc.Range("fac")

    Me.cbo_fac1.AddItem c_fac.Value
    Me.cbo_fac1.List(Me.cbo_fac1.ListCount - 1, 1) = c_fac.Offset(0, 1).Value

    Me.cbo_fac2.AddItem c_fac.Value
    Me.cbo_fac2.List(Me.cbo_fac2.ListCount - 1, 1) = c_fac.Offset(0, 1).Value

    Me.cbo_fac3.AddItem c_fac.Value
    Me.cbo_fac3.List(Me.cbo_fac3.ListCount - 1, 1) = c_fac.Offset(0, 1).Value

Next c_fac
于 2012-10-10T22:27:30.677 回答