Unable to query named range on sheet with spaces in name in Excel

a 夏天 提交于 2019-12-01 18:16:06

Would it be possible to use an excel range instead of named range? I got the following to work:

SELECT * FROM [Report 1$A4:P]

I'm getting the sheet name from the GetOleDbSchemaTable() method and removing the apostrophes. The sheetname with apostrophes does not work for me with a range.

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

Below query would work. Just make sure the named range Ingredients exist in sheet With Space. Also save the workbook.

strQuery = "Select * from [With Spaces$Ingredients]"

Alternatively you can use below

strQuery = "Select * from [With" & Chr(32) & "Spaces$Ingredients]"

The name of the sheet with spaces followed by named range can be written as ['My Sheet$'MyData]

Here is how you get to list the tables contained in the workbook

1) Code to get the list of tables in the workbook

dim i as Integer

Set objRecordSet = objConn.OpenSchema(adSchemaTables)
Do While Not objRecordSet.EOF
    i = 1
    For i = 0 To objRecordSet.Fields.Count - 1
        Debug.Print objRecordSet.Fields(i).Name, objRecordSet.Fields(i).Value
    Next

    objRecordSet.MoveNext
Loop

EDIT: For your scenario, it will be

strQuery = "Select * from ['With Spaces$'Ingredients]"

EDIT2: I am sorry, I pasted the wrong code the first time. Please use the above code in the listing 1 and look for TABLE_NAME in the immediate window. The listing of named ranges prefixed with sheet name will be shown against TABLE_NAME (on which you can query).

Also, make sure that the named range is scoped to the worksheet. Make sure that the casing of the sheet name and range name matches with query.

Another late entrance to the party...

I couldn't get any of the responses here to work for the entire sheet, so I made a named range for the whole sheet (select all cells and give them a name - I called them POList) and referred to that thus:

UPDATE [POList] SET..... etc

So no single quotes, no backticks, no $ sign, not even the sheet name.

Having said that, the workbook in question only has the one sheet (which DOES have spaces in the name).

This works using Excel 2002 (!) and the following connection code

Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .ConnectionString = "Data Source=C:\Purchase Req No. List.xls; Extended Properties=Excel 8.0;"
    .Open
End With

Obviously this won't work for everyone's situation and is a bit of a kludgey workaround, but maybe someone will find it useful...

I was having this same issue and was able to solve without a named range. In addition, as a two-fold part of what my issue was, make sure there are no trailing spaces in the worksheet name. Try...

strQuery = "Select * from ['With Spaces$']"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!