使用vba在Word中访问Excel中特定列的数据

问题描述 投票:0回答:1

我正在尝试在 MS Word 中使用 VBA 访问 excel 数据。但我无法从特定列中获取最后使用的行。我正在尝试从特定的列获取数据以在我的 Word 文件中构建下拉列表

我试过这个:

Private Sub Test_Form()

    Dim xlApp As Object
    Dim xlWorkbook As Object
    Dim xlSheet As Object
    Dim lastRow As Long
    Dim i As Long
    Dim excelFilePath As String

    excelFilePath = "path...\File.xlsx"
    
    On Error Resume Next
    Set xlApp = GetObject(, "Excel.Application")
    If Err Then
        Set xlApp = CreateObject("Excel.Application")
    End If
    
    Set xlWorkbook = xlApp.Workbooks.Open(FileName:=excelFilePath, ReadOnly:=True)
    Set xlSheet = xlWorkbook.Sheets(1)

    lastRow = xlSheet.Cells(xlSheet.Rows.Count, 1).End(xlUp).Row 'here is where I get the problem

    xlWorkbook.Close False
    xlApp.Quit
    
    Set xlSheet = Nothing
    Set xlWorkbook = Nothing
    Set xlApp = Nothing

End Sub

在我的 Excel 文件中,我仅在前 23 行的第一个列中包含数据。 然而,当我用

MsgBox
检查时,我得到lastRow=0。 我也尝试过
lastRow = xlSheet.usedRange.Rows.Count
,这里我实际上得到了 23 但我无法指定列。 有人有想法吗?

excel vba ms-word dropdown
1个回答
0
投票

通过改变来发挥作用

lastRow = xlSheet.Cells(xlSheet.Rows.Count, 1).End(xlUp).Row

至:

lastRow = xlSheet.Range("A1").CurrentRegion.Rows.count
© www.soinside.com 2019 - 2024. All rights reserved.