我尝试从所选工作簿中的多个工作表中收集数据,但是我得到了运行时错误' 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
答案 0 :(得分:0)
AutoFit
是Range
对象的方法,而不是WorkSheet
对象。
类似于:
wbk.Worksheets(outputSheetName).UsedRange.AutoFit
应该有效