从选定工作簿的多个工作表中收集数据

Gathering data from multiple worksheets from a selected workbook

我正在尝试从选定工作簿的多个工作表中收集数据,但出现 运行 时间错误“9”下标超出范围。

我正在使用以下代码:

Sub MultipleSheets()

Dim filepath As Variant
Dim outputFilePath As String
Dim outputSheetName As String

'To which file and sheet within the file should the output go?
outputFilePath = "C:\Users\z003k50s\Desktop\Test\Output.xlsx"
outputSheetName = "Sheet1"

For Each filepath In Application.GetOpenFilename(FileFilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
    Dim conn As New ADODB.Connection
    Dim schema As ADODB.Recordset
    Dim sql As String
    Dim sheetname As Variant

    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=""" & filepath & """;" & _
            "Extended Properties=""Excel 12.0;HDR=Yes"""
        .Open
    End With
    Set schema = conn.OpenSchema(adSchemaTables)
    For Each sheetname In schema.GetRows(, , "TABLE_NAME") 'returns a 2D array of one column
 sql = "SELECT * FROM [" & sheetname & "]"

        'If you want a specific range, you can change that in the last line:
        'Dim topLeft As String, bottomRight As String
        'topLeft = "D4"
        'bottomRight = "F100"
        'sql = _
        '    "INSERT INTO [" & outputSheetName & "$] IN """ & outputFilePath & """ ""Excel 12.0;"" " & _
        '    "SELECT * " & _
        '    "FROM [" & sheetname & topLeft & ":" & bottomRight & "]"

        conn.Execute sql
    Next
Next

Dim wbk As Workbook
Set wbk = Workbooks.Open(outputFilePath)
wbk.Worksheets(outputSheetName).AutoFit

End Sub

感谢 Zev Spitz 提供代码示例。

当我调试时,它突出显示了以下行:

wbk.Worksheets(outputSheetName).AutoFit

AutoFitRange 对象的方法,而不是 WorkSheet 对象的方法。

所以像这样:

wbk.Worksheets(outputSheetName).UsedRange.AutoFit

应该可以