Search code examples
excelexcel-2007vba

Compile Error: Duplicate declaration in current scope


I'm trying to gather data from multiple sheets in a selected workbook. I'm using the following code:

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

When I debug it highlights:

 conn As New ADODB.Connection

I'm very new to Excel VBA and I don't know what it means.


Solution

  • Snippet of your code:


    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
    

    As you can see from my comments, you have used conn and then tried to dimension (Dim) it, which is why you are getting the compile error.