0

为什么这一直给我1004?Worksheet Name 和 Codename 是一样的,所以可以引用,那为什么我一直得到 1004

Public Sub UserForm_Initialize()
Dim coLoc As Integer
Dim i As Integer
Dim ia As Integer

coLoc = ThisWorkbook.Worksheets("Company").Range(Cells(2, 1), Cells(Rows.count, 1).End(xlUp)).count
For i = 2 To coLoc Step 1
ComboBox1.AddItem (ThisWorkbook.Worksheets("Company").Cells(i, 2).Value)
Next i   

End Sub

请给我一些清晰度,因为键盘将穿过屏幕。

4

3 回答 3

2

我无法对其进行测试,但我认为当您为 Coloc 分配值时它会崩溃。VBA 不知道您在说哪些“单元格”。我知道这听起来可能违反直觉,但您需要在 Range 内指定它,而不是之前。

尝试 :

With ThisWorkbook.Worksheets("Company")
    coLoc = Range(.Cells(2, 1), .Cells(.Rows.count, 1).End(xlUp)).count
End With
于 2013-07-27T21:19:01.660 回答
2

如果没有更多细节,不确定是什么引发了这个特定错误,但请尝试完全限定您的范围对象。

这使用了稍微不同的迭代方法:

Public Sub UserForm_Initialize()
    Dim wb as Workbook: Set wb = ThisWorkbook
    Dim ws as Worksheet: Set ws = wb.Sheets("Company")
    Dim colRange as Range
    Dim cl as Range


    Set colRange = ws.Range(ws.Cells(2, 1), ws.Cells(ws.Rows.count, 1).End(xlUp))
    For each cl in colRange.Cells
        ComboBox1.AddItem cl.Value
    Next 

End Sub
于 2013-07-27T21:21:18.353 回答
1

作为替代方案,我喜欢用来List填充组合框:

Private Sub UserForm_Initialize()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim colRange As Range

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Company")
    Set colRange = ws.Range(ws.Cells(2, 1), ws.Cells(Rows.Count, 1).End(xlUp))

    ComboBox1.List = colRange.Value
End Sub

没有必要限定Rows.Count,尽管它没有害处。

于 2013-07-27T22:58:00.527 回答