【发布时间】:2015-09-15 21:01:24
【问题描述】:
我正在尝试从选定工作簿的多个工作表中收集数据。我正在使用以下代码:
Sub Multiplesheet()
Dim filepath As Variant
Dim outputFilePath As String
Dim outputSheetName As String
Dim sql As String
Dim wbk As Workbook, wks As Worksheet
Dim rng As Excel.Range
Dim sheetname As Variant
'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)
Set schema = conn.OpenSchema(adSchemaTables)
For Each sheetname In schema.GetRows(, , "TABLE_NAME") 'returns a 2D array of one column
sql = sql & _
"UNION ALL SELECT F1 " & _
"FROM [" & sheetname & "]" & _
"IN """ & filepath & """ ""Excel 12.0;"""
Next
Next
sql = Mid(sql, 5) 'Gets rid of the UNION ALL from the first SQL
Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=""" & filepath & """;" & _
"Extended Properties=""Excel 12.0;HDR=No"""
.Open
Set rs = .Execute(sql)
Set wbk = Workbooks.Open(outputFilePath, , True)
Set wks = wbk.Sheets(outputSheetName)
wks.Cells(2, 1).CopyFromRecordset rs
wks.Columns.AutoFill
.Close
End With
End Sub
当我调试时它会突出显示:
conn As New ADODB.Connection
我是 Excel VBA 的新手,我不知道它是什么意思。
【问题讨论】:
-
正如它所说的 - 你复制了一个声明。在您的代码中,
conn在您Dim它之前已经使用过,所以要么已经有一个名为conn的公共变量,conn在您Dim它之前被用作此代码中的变体会导致编译错误,或者您没有向我们展示完整的代码。 -
将
Option Explicit放在声明部分的模块表顶部。还建议您进入工具 ► 选项并在 Require Variable Declaration 旁边打勾,以避免将来出现这些问题。 -
我已经给你们发了完整的代码,但我看不到我在哪里复制了声明。
-
如果你不需要在使用前声明你的变量,那么它们会被即时创建,因为 conn 是
Set schema = conn.OpenSchema(adSchemaTables)。然后,您尝试在几行之后将其声明为Dim conn As New ADODB.Connection,但它已经通过它的使用被“声明”了。
标签: excel excel-2007 vba