Excel VBA 在 sheet 上引用错误 table

Excel VBA referancing wrong table on sheet

我在单个 sheet tblMaintenanceData、tblVehicleDailyLog 和 tblDriverList 上有三个 table。并使用表格填写tables。这些表格使用 ComboBox 下拉列表,由这些 table 中的数据填充——一个用于车辆 ID,第二个用于驾驶员姓名。

车辆 ID 下拉列表正确填写。 Driver Name Dropdown 没有;而不是在开始将数据加载到下拉列表时抛出错误(下面的斜体和粗线)。

使用 Debug.Print 我发现 iRows 和 iColumns 填充了正确的值。 Cells(x, y).Value 指向页面上的第一个 table (tblMaintenanceData),而不是 tblDriverList。那我做错了什么?

谢谢

Sub FillDriverList()


 '  This fills the drop down list of available drivers for each of the user created forms.
    Const WorkSheetName = "MaintenanceData"
    Const WorkTableName = "tblDriverList"

    Dim tbl As ListObject
    Dim lRows As Long, lColumns As Long, lWork01 As Long
    Dim i As Integer
    Dim ws As Worksheet
    Dim CurrentPageState As String
    Dim CurrentPageProtection As String

    Set ws = ThisWorkbook.Sheets(WorkSheetName)

    ' this saves the Page State for Visibility and Protection, allowing to be reset after working with the page
    CurrentPageState = ws.Visible
    CurrentPageProtection = ws.ProtectContents
    ws.Visible = xlSheetVisible
    ws.Select

    Set tbl = ws.ListObjects(WorkTableName)

    With tbl.DataBodyRange
        lRows = .Rows.Count
        lColumns = .Columns.Count
    End With

'Debug.Print lRows & " / " & lColumns

    For i = 1 To lColumns
        If Cells(1, i).Value = "DRIVER LIST" Then lWork01 = i

'Debug.Print Cells(1, i).Value

    Next

'Debug.Print Cells(2, 1).Value & " - " & Cells(3, 1).Value & " - " & Cells(4, 1).Value

    For i = 1 To lRows
        With DataEntry06
            ***.cmbInput05.AddItem ws.Cells(i, lWork01).Value***
        End With
    Next


CLOSE_SUB:
    ws.Visible = CurrentPageState
    If CurrentPageProtection = True Then
        ws.Protect UserInterfaceOnly:=True
    End If

    Set ws = Nothing
    Set tbl = Nothing


End Sub

查看数据表 View of Data Tables

尝试用“tbl.DataBodyRange.Select”代替 With / End With

我认为您在这里所做的工作比您需要做的更多 - 您可以更多地利用 listobject 属性和方法。

简化版:

Sub FillDriverList()
    
    Const WorkSheetName = "MaintenanceData"
    Const WorkTableName = "tblDriverList"

    Dim tbl As ListObject
    
    Set tbl = ThisWorkbook.Sheets(WorkSheetName).ListObjects(WorkTableName)
    
    'loop each cell in the "DRIVER LIST" column
    For Each c In tbl.ListColumns("DRIVER LIST").DataBodyRange.Cells
        DataEntry06.cmbInput05.AddItem c.Value
    Next c

End Sub