MS Access VBA acImport 工作表名称,包含空格和范围

Bil*_*itt 5 import ms-access vba spreadsheet ms-access-2010

我正在构建一个带有名为“Go”的按钮的表单,用于从 Excel 文件导入特定 Excel 工作表的特定范围。另一个子/函数负责将表单上的文件名放在名为 text_filepathdata 的字段中。

我发现工作表名称中的空格是有问题的,但是可以通过使用特殊引号来解决。

Dim sheetname As String
sheetname = "'Commit Volumes!'"
DoCmd.Transferspreadsheet acImport, acSpreadsheetTypeExcel12, _
    "lcl_ImportedFile", text_filepathdata, True, sheetname
Run Code Online (Sandbox Code Playgroud)

这可行,但由于特殊引用,我无法指定除工作表名称之外的范围...(即“'Commit Volumes!A6:Z5000'”不起作用,两者的串联也不起作用诸如“‘Commit Volumes’”和“A6:Z5000”之类的作品)

我尝试了各种引用和连接方式,但唯一有效的是:

sheetname = "'Commit Volumes!'"
sheetname = "'Commit Volumes$'"
sheetname = "CommitVolumes!A6:Z5000"
Run Code Online (Sandbox Code Playgroud)

Excel 工作表无法修改,因为它来自另一个系统,并且文件(更新后)必须上传回该系统。

这是我的代码:

Private Sub button_Go_Click()
On Error GoTo Err_button_Go_Click

Dim sheetname As String
sheetname = "'Commit Volumes!'"

If IsNull(text_filepathdata) Or text_filepathdata = "" Then
    MsgBox "Please browse and select a valid file to import.", _
        vbCritical, "Invalid File"
Else
    DoCmd.OpenForm "f_PleaseWait_Processing", acNormal, , , acFormReadOnly, acWindowNormal
    If ifTableExists("lcl_ImportedFile") = True Then
        DoCmd.DeleteObject acTable, "lcl_ImportedFile"
    End If
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12,_
        "lcl_ImportedFile", text_filepathdata, True, sheetname

'Call module to process the imported data
        Call MainProcess
    End If

Exit_button_Go_Click:
    Exit Sub

Err_button_Go_Click:
    MsgBox Err.Number & " - " & Err.Description
    Resume Exit_button_Go_Click

End Sub
Run Code Online (Sandbox Code Playgroud)

根据问题,我收到两条不同的错误消息。

如果名称中有空格,我会得到: Run-time error 3129: Invalid SQL statements; 应为“DELETE”、“INSERT”、“PROCEDURE”、“SELECT”或“UPDATE”。

如果名称有问题,否则我会得到:运行时错误 3011:Microsoft Access 数据库引擎找不到对象“Commit Volumes$A1:Z5000”。确保该对象存在并且其名称和路径拼写正确。如果“Commit Volumes$A1:Z5000”不是本地对象,请检查您的网络连接或联系服务器管理员。

任何帮助将不胜感激!

账单

我尝试过的变体:

sheetname = "'Commit Volumes'!A6:Z5000"; 
sheetname = "'Commit Volumes!'A6:Z5000" 
sheetname = "'Commit Volumes$'A6:Z5000" 
sheetname = "'Commit Volumes'$A6:Z5000" 
sheetname = "'Commit Volumes'$A$6:$Z$5000" 
sheetname = "'Commit Volumes!'$A$6:$Z$5000" 
sheetname = "'Commit Volumes$'$A$6:$Z$5000"
Run Code Online (Sandbox Code Playgroud)

Sco*_*man 0

这就是您所需要的:

'Commit Volumes'!A6:Z5000

当工作表名称包含空格或破折号时,Excel 会在工作表名称本身周围放置单引号,而不是在整个引用周围放置单引号。

所以:

sheetname = "'Commit Volumes'!A6:Z5000"
Run Code Online (Sandbox Code Playgroud)