0

我在 Excel VBA 宏中初始化用户窗体。当我去填充组合框中的项目时,我陷入了无限循环,但我不知道为什么。这是我的代码:

Private Sub UserForm_Initialize()

  'Populate the combobox with the months
  Me.cboCurrMth.SetFocus
  Dim cMth As Range
  Dim ws As Worksheet
  Set ws = Sheet1
  For Each cMth In ws.Range("months")
      With Me.cboCurrMth
          .AddItem cMth.Value
          .List(.LineCount - 1, 1) = cMth.Offset(0, 1).Value
      End With
  Next cMth

End Sub

命名范围“月”包括所有 12 行和 2 列,其中第一列是整数(从 1 到 12),第二列是每个月的字符串名称。

任何人都明白为什么这个循环不会终止?谢谢。

4

2 回答 2

1

I have wrote the following code and it is worked for me. I am using Excel 2003.

ActiveSheet.Shapes("cmbMonths").Select

Dim currMonth As Range
With Selection
    For Each currMonth In Range("Months")
        .AddItem currMonth.Value
    Next
End With

This line ".List(.LineCount - 1, 1) = cMth.Offset(0, 1).Value" is giving error for me 'Saying member not found"

Please select your month cells once again and give the name for the selected range and try again. Hope it works.

于 2012-05-26T03:12:49.047 回答
1

您应该很少在生产 VBA 代码中选择单元格或范围。但是,它对于调试目的非常有帮助。

.select在循环中添加一个,For Each然后单步执行您的代码。您应该能够找出问题所在。

Private Sub WhyAmIInfinite()

  'Loop through and select the months
  Dim cMth As Range
  Dim ws As Worksheet
  Set ws = Sheet1
  For Each cMth In ws.Range("months")
        cMth.Select
  Next cMth

End Sub

我设置了一个工作表,其范围与您描述的完全一样,并且循环按我的预期退出。我从示例中删除了组合框,因为我想隔离循环本身。

于 2012-05-26T12:38:01.207 回答