编译错误:当前范围内的重复声明

时间:2015-09-15 12:09:17

标签: excel excel-vba excel-2007 vba

我尝试从选定工作簿中的多个工作表中收集数据。我使用以下代码:

Sub Test()
    Debug.Print GetBaseName("mdl_FILE_Functions.bas")
End Sub

Public Function GetBaseName(FileName As String) As String
    Dim FS As Object
    Set FS = CreateObject("Scripting.FileSystemObject")
    GetBaseName = FS.GetBaseName(FileName)
End Function

当我调试它时突出显示:

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

我对Excel VBA很陌生,我不知道它意味着什么。

1 个答案:

答案 0 :(得分:0)

您的代码片段:

For Each filepath In Application.GetOpenFilename(FileFilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
'----------
    Set schema = conn.OpenSchema(adSchemaTables) '<~~~ HERE YOU HAVE USED 'conn'
'----------

    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 '<~~~ already exists, so duplicate declaration
'---------

Dim rs As ADODB.Recordset
 With conn

从我的评论中可以看出,您使用了conn然后尝试维度(Dim),这就是您收到编译错误的原因。