Unable to query dynamically named range on Excel sheet using ADO - vba

Suppose I have an Excel Sheet named Adjustments stored in a variable called wksName and, on that sheet, I have a named range defined as follows if you look in the Name Manager:
tblData =OFFSET(Adjustments!$A$1,0,0,COUNTA(Adjustments!$A:$A),4)
So that it expands to as many rows as we have data in columns A thru D.
Now I have the following code in my VBA module:
Set ExcelCon = CreateObject("ADODB.Connection")
Set ExcelRecSet = CreateObject("ADODB.Recordset")
ExcelCon.ConnectionString = "Provider='Microsoft.Jet.OLEDB.4.0';" & _
"Data Source='" & ThisWorkbook.FullName & "';" & _
"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
'Get the data for the update:
ExcelCon.Open
' Get the data from the spreadhseet for the update statement
Set ExcelRecSet = ExcelCon.Execute("SELECT * FROM [" & wksName & "$tblData]")
When I try and run this code, I get the error:
Run-time error '-2147217865 (80040e37)':
The Microsoft Jet database engine could not find the object 'Sheet1$tblData'.
Make sure the object exists and that you spell its name and the path name correctly.
Is this a limitation to using ADO - Named ranges can not be dynamically defined - Or is there a way I can get this to work?
Thanks!!

As stated in the comments, the code that ended up working for me (for those of you that may find you have the same issue) was something along the lines of:
Set ExcelRecSet = ExcelCon.Execute("SELECT * FROM [" & wksName & "$" & _
wks.Range("tblData").Address(0, 0) & "]")
This definitely works, but if there was a way to select a variable range without having to reference it as above, I'd love to see the way to do that.
Thanks!!

Related

Insert Query/Select Query works in access, but not in vba

I have created a query that works great with no errors in Access, and while trying to translate this to my vba setup I can't figure out why I am not getting any values, even though the query clearly works in access, and causes no errors on the VBA side.
Pulling my hair out here, I have created a side table to see if I could "pseudo-insert" the calculated value, but I get the same issue as above - insert works with no errors in access, goes through in vba with no issues, but doesn't actually insert any data.
I have copied the string queries while pausing code to make sure EVERYTHING matches up between the Access query that works and the VBA query, and haven't found any differences.
I read somewhere since I am trying to pull a "first line" data piece that there may be some HDR setting that I could change, but when I tried to apply any fixes I found they opened another instance of excel and opened a dialogue box.
Please let me know what I am doing wrong here.
Public Function PullNextLineItemNumB(QuoteNum) As Integer
Dim strQuery As String
Dim ConnDB As New ADODB.Connection
Dim myRecordset As ADODB.Recordset
Dim QuoteModifiedNum As String
ConnDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data
source=" & ThisWorkbook.Path & "\OEE Info.accdb"
'Query to try and make Access dump the value "18" into the table so I can
grab it after the query is finished, sidestepping excel not working
strQuery = "INSERT INTO TempTableColm (TempColm) SELECT
MAX(MID([Quote_Number_Line],InStr(1,[Quote_Number_Line]," & Chr(34) & "-"
& Chr(34) & ")+1)) AS MaxNum from UnifiedQuoteLog where Quote_Number_Line
like '" & QuoteNum & "*'"
ConnDB.Execute strQuery
'Original query, returns "18" as expected in Access, and null or empty in
the recordset
strQuery = "SELECT MAX(MID([Quote_Number_Line],InStr(1,
[Quote_Number_Line]," & Chr(34) & "-" & Chr(34) & ")+1)) from
UnifiedQuoteLog where Quote_Number_Line like '" & QuoteNum & "*'"
Set myRecordset = ConnDB.Execute(strQuery)
Do Until myRecordset.EOF
For Each fld In myRecordset.Fields
Debug.Print fld.Name & "=" & fld.Value
Next fld
myRecordset.MoveNext
Loop
myRecordset.Close
Set myRecordset = Nothing
ConnDB.Close
Set ConnDB = Nothing
End Function
Actual output from access is "18" which is expected, output from excel's vba recordset is always null or empty string.
It appears I solved the problem, while looking into this apparently the excel operator using ADODB with access is % for LIKE and NOT * (because reasons). As soon as I made that change everything started working.
Can someone explain why that is a thing? I really want to understand why this was a design choice.

Excel VBA Recordset SQL - No value given for required parameters

Whilst the title of this question is similar to other questions asked in the past, I could not via limited searching on Google or SE find an answer that helped me with my problem below.
I am trying to pick up data from an excel sheet for processing. After finding that a more complex SQL statement with a join gave an error, I looked deeper and found the following;
The below SQL statement runs fine:
SELECT [DNSHEET$].[DNS] FROM [DNSHEET$]
However the below SQL statement does not & this gives the error stated in title later.
SELECT [DNSHEET$].[DNK] FROM [DNSHEET$]
I use the code below for running either SQL statement - they are saved in sql1 which is defined as a string.
rs.execute(sql1), cn
Where rs is the Recordset and cn the connection.
cn is defined as:
Set cn = CreateObject("ADODB.Connection")
With cn
.provider="Microsoft.ACE.OLEDB.16.0"
.ConnectionString="Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _ "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.open
End with
DNS and DNK headers are correctly named and match headers on DNSHEET sheet.
DNS is populated with string data, DNK contains integers from 1 to circa 25000.
Update: This issue has been worked around by closing and reopening the excel workbook. Then both of the SQL queries could run.
Hence another question is why this arises and how to find out what the cause of the problem is?

Connecting to Access 2016 from Excel 2016 with VBA

I'm very new to VBA, and I've been trying to write some code in Excel 2016 that will, when a button is pressed, take a range of cells and write them to a table that I've set up in an Access 2016 database. I'm working out of an .xlsm workbook right now.
I've been basing my code off of the bulk-insert method (building an SQL "INSERT INTO" statement) that the submitter posted as an edit to this previous StackOverflow question Using Excel VBA to export data to MS Access table .
So far, here is the VBA I have written (or at least the part of it dealing with the importing into Access). When I run it, I get the error "Run-time error '-2147467259 (80004005)': Could not find installable ISAM.". I think the issue is in my connection string, which I've been having trouble with since I can't find any examples of properly-formatted connection strings on the Internet that use Access 2016 and Excel 2016 (mostly older versions).
' Set up the transfer into Access
Dim dbPath As String, dbWb As String, dbWs As String, scn As String, dsh As String, ssql As String
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\MyDatabase.accdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is the named range of data to be written to Access
' Open the connection with Access
cn.Open scn
' Create an SQL "Insert" statement using the name dsh developed earlier
ssql = "INSERT INTO DataPortfolio ([Field1], [Field2], [Field3]) "
ssql = ssql & "SELECT * FROM [Excel 16.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
' Execute the SQL statement
cn.Execute ssql
Can anyone see where I may be going wrong? I assume it's in the connection string (scn), but I'm not sure.
Any help is appreciated! Many thanks.

How to copy data from non-linked to linked table in Access 2010 using VBA

So what I'm trying to do is to either copy data from an Access local table to a linked table on a SQL Server. I'd like this to work via a macro so it can be triggered upon opening a report. Or I could just bypass the linked table and insert directly to the remote server.
What I'm having a difficult time finding is the proper syntax to accomplish this. It should be very easy but apparently it's not.
Public Sub CopyPT()
Dim strSQL As String
Dim strConnect As String
Dim strDatabase As String
Dim strTableName As String
ODBC_String = "ODBC;DRIVER={SQL Server};SERVER=aaa;DATABASE=bbb;UID=ccc;PWD=ddd;" _
& "LANGUAGE=us_english;TRUSTED_CONNECTION=No"
' Id also like to truncate the Destination table here too
strSQL = "SELECT * INTO dbo_DESTINATION_TABLE IN [" & ODBC_String & "]" _
& " FROM [ACCESS_LOCAL_TABLE];"
DoCmd.RunSQL strSQL
MsgBox "Success!"
End Sub
Either I need to get the proper format for the IN statement, which doesn't appear to have ODBC option, or I need another method to copy to the linked table. Such a simple copy and paste line by line macro - which I also can't find anywhere since most sane people would just write a query.
Thanks!

How to address a sheet with (2) in it's name with ADO

So I am using ADO to import data from several workbooks in a folder with several tabs in them. I have been able to set up all of the tabs to work with this except a tab named "MAT. (2)". When I use the code below, it gives me an error saying "Invalid Bracketing". I can't change the name of the tab due to it being a controlled document. Is there a way I can put the tab name in a format that will be accepted or possibly some way that I could address "Sheet3" instead (I already tried that and it threw an error saying it couldn't find the object).
Set rs = dbConnection.Execute("SELECT * FROM [" & SourceSheet$ & "$" & SourceRange & "]")
Set TargetCell = Range(TargetRange).Cells(1, 1)
TargetCell.CopyFromRecordset rs
Edit -
The connection string that I am using is as follows:
dbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=No"";"
You could try using single or double quotes to escape the name, rather than brackets. What provider are you using to connect? I had an issue with connecting to a SQL Server database with a hyphenated name. I tried everything I could think of to escape the name, but it wouldn't work. I ended up solving the problem by switching from an ODBC connection to OLE DB connection. Maybe try the ACE OLEDB 12.0 provider and see if you can get it to work that way. OLE DB excel connstrings
EDIT:
Have you tried escaping the database name in backticks?
I'm thinking the . is the issue as this character is usually illegal as a database or table name in most SQL based RDBMS's. So try something like:
Set rs = dbConnection.Execute("SELECT * FROM `"& SourceSheet$ & "$" & SourceRange &`"
or possibly
Set rs = dbConnection.Execute("SELECT * FROM [`" & SourceSheet$ & "$" & SourceRange & "`]"
I'm not sure if either of these will work, but is worth a shot. If you can, you might want to remove the . from any worksheet names as it might cause some funny problems.