如何使用使用ADODB移动数据的Excel VBA宏选择动态工作表名称?

时间:2015-06-26 15:37:40

标签: excel vba excel-vba adodb

我使用宏通过ADODB连接在工作簿中移动数据。当我从已关闭的工作簿中选择数据时,我需要将工作表名称标记为动态。但是,当使用我的字符串变量作为名称时,代码将不会运行。

Public Sub MoveData()

    Dim fileName As String
        fileName = Worksheets("Cover").range("B5").Value

    Dim path As String
        path = "C:\Users\(user)\Documents\(folder)\" & fileName & ".csv"

    Dim currentWB As Workbook
    Set currentWB = ThisWorkbook

    Dim openWB As Workbook
    Set openWB = Workbooks.Open(path)

    Dim openWs As Worksheet
    Set openWs = openWB.Sheets(fileName)

    Dim cn As ADODB.Connection
    Set cn = New ADODB.Connection
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & path & ";" & _
                    "Extended Properties=Excel 12.0 Xml;"
        .Open
    End With

    strQuery = "SELECT * FROM [filename$C2:C100]"

    Set cmd = New ADODB.Command
    With cmd
        .ActiveConnection = cn
        .CommandText = strQuery
    End With

    Dim rst As New ADODB.Recordset
    With rst
        .ActiveConnection = cn
        .Open cmd
    End With

    currentWB.Worksheets("Bms").range("C7").CopyFromRecordset rst

    openWB.Close

End Sub

问题出现在strQuery = "SELECT * FROM [fileName$C2:C100]"中。工作表名称将始终与文件名相同。代码似乎将fileName作为文字字符串,我不想要。如何让工作表名称保持动态?

2 个答案:

答案 0 :(得分:4)

变化:

strQuery = "SELECT * FROM [filename$C2:C100]"

为:

strQuery = "SELECT * FROM [" & filename & "$C2:C100]"

答案 1 :(得分:3)

您需要使用&将文件名连接到字符串中以进行连接,例如:

strQuery = "SELECT * FROM [" & filename & "$C2:C100]"