简体   繁体   English

使用VBA将Excel表或命名范围导出到Access

[英]Export Excel table or named range to Access using VBA

I have the following code that I am using to insert values from an Excel sheet to an Access table. 我使用以下代码将值从Excel工作表插入到Access表中。 It works 有用

Dim cn As ADODB.Connection
Dim strQuery As String

Set cn = New ADODB.Connection
With cn

.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & Application.CurrentProject.Path & "\Excel\testdb.accdb;"
.Open
End With

ssql = "INSERT INTO Table1
SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=Z:\Docs\Test.xls].[Sheet1$]"

I know that I can also do the same with a specified range by doing the following: 我知道我也可以通过执行以下操作在指定范围内执行相同操作:

ssql = "INSERT INTO Table1
SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=Z:\Docs\Test.xls].[Sheet1$a1:a4]"

However, after trying everything and looking everywhere, I can't figure out how to do this for an Excel table or named range.Is it possible? 但是,在尝试了所有内容并四处查看之后,我不知道如何对Excel表或命名范围执行此操作,这可能吗? Can anyone help? 有人可以帮忙吗?

actually, I was able to do it by: 实际上,我能够通过以下方式做到这一点:

SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=Z:\Docs\Test.xls].range_name"

The problem I was having before was that the Excel table I was using was created by a connection to external data (actually the same Access database). 我以前遇到的问题是,我使用的Excel表是通过与外部数据(实际上是相同的Access数据库)的连接创建的。 I tried to import and link to the Excel table from Access and was only able to do so when the Excel file was closed. 我试图从Access导入并链接到Excel表,但是只有在关闭Excel文件时才能这样做。 I guess this is to prevent some kind of circular referencing. 我想这是为了防止某种循环引用。

You don't need to specify the workbook again in the WHERE clause since it is already referenced in the connection string. 您无需在WHERE子句中再次指定工作簿,因为它已在连接字符串中被引用。

To answer your question, the scope of the defined name determines the syntax: 为了回答您的问题,定义名称的范围决定了语法:

SELECT * FROM [YourSheetName$SheetScopedNamedRange]

or 要么

SELECT * FROM WorkbookScopedNamedRange

Note hat there are no square brackets in the second example. 请注意,第二个示例中没有方括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM