无法在Excel上使用名称中的空格查询工作表上的命名范围

use*_*491 5 sql excel vba excel-vba named-ranges

我有一个包含多个工作表的工作簿,每个工作表都有相同的命名范围集(IE它们的范围是工作表,而不是工作簿).

我想根据任何工作表上的命名范围进行查询.有些工作表的名称没有空格,而其他工作表的名称则带有空格.

我可以很容易地为没有空格的那些做这个,但用空格做这个的语法逃避了我(和一小时的谷歌).

命名范围是"成分",一张名为"NoSpaces",另一张名为"With Spaces"

这是适用于"NoSpaces"表的代码:

sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dictNewRecipesToCheck(arrKeys(0)) & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1;"""
strQuery = "Select * from [NoSpaces$Ingredients]"
Set objConn = New ADODB.Connection
Set objRecordSet = New ADODB.Recordset
objConn.Open sConnString
objRecordSet.Open strQuery, objConn
Run Code Online (Sandbox Code Playgroud)

我已经为"With Spaces"表单尝试了以下所有内容:

strQuery = "Select * from [With Spaces$Ingredients]"
strQuery = "Select * from ['With Spaces'$Ingredients]"
strQuery = "Select * from ['With Spaces$'Ingredients]"
strQuery = "Select * from [With_Spaces$Ingredients]"
Run Code Online (Sandbox Code Playgroud)

每次,我得到"Microsoft Access数据库引擎找不到对象..."错误.

正如我所提到的,它适用于名称中没有空格的所有工作表.

任何帮助使这个工作在带空格的工作表上,将非常感谢.

谢谢!

基于以下评论的更新:

Excel 2007

sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileLoc & ";Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"""
Run Code Online (Sandbox Code Playgroud)

当运行@shahkalpesh提供的模式代码时,它将TABLE_NAME列为两个命名范围的"成分"(即使每个范围都限定为不同的工作表).
使用此驱动程序,即使[NoSpaces $ Ingredients]也无效.

sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFileLoc & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1;"""
Run Code Online (Sandbox Code Playgroud)

当运行@shahkalpesh提供的模式代码时,它将TABLE_NAME列为"NoSpaces $ Ingredients"和"'With Spaces'$ Ingredients".有了这个驱动程序,[NoSpaces $ Ingredients]工作正常(它没有ACE驱动程序).
但是,使用模式报告的确切名称,['With Spaces'$ Ingredients]不起作用.

Excel 2013

sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileLoc & ";Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"""
Run Code Online (Sandbox Code Playgroud)

当运行@shahkalpesh提供的模式代码时,它将TABLE_NAME列为"NoSpaces $ Ingredients"和"'With Spaces $'Ingredients".有了这个驱动程序,[NoSpaces $ Ingredients]工作正常,但['With Spaces'$ Ingredients]不起作用.

最后,请参阅http://db.tt/3lEYm2g1获取在Excel 2007中创建的示例表,该表在(至少)2台不同的计算机上存在此问题.

小智 6

是否可以使用excel范围而不是命名范围?我得到以下工作:

SELECT * FROM [Report 1$A4:P]
Run Code Online (Sandbox Code Playgroud)

我从GetOleDbSchemaTable()方法获取工作表名称并删除撇号.带有撇号的工作表名称对我来说不适用于范围.

if (tableName.Contains(' '))
            tableName = Regex.Match(tableName, @"(?<=')(.*?)(?=\$')", RegexOptions.None).Value + "$";
Run Code Online (Sandbox Code Playgroud)