On click I'm getting error "Argument is not optional" - vba

I have tried the following code in Excel. It is connecting successfully. I want to get input values from user. To get value from user, I have used Range.Value("N3") and Range.Value("N4").
It works fine without getting value in that way. But when I add value on excel sheet and click the button to fetch records,
it gives me the error
"Argument is not optional"
If someone here can check this?
Here is the code :
Private Sub CommandButton1_Click()
Dim mon As String
Dim yea As String
mon = Range.Value("N3")
yea = Range.Value("N4")
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=inFlow;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "exec dbo.ReportTotalCompanyMonthlySales ' & yea & ',' & mon&'"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
End Sub

Try this:
mon = Range("N3").Value
instead of
mon = Range.Value("N3")

Related

Run Excel SQL on Existing Sheet - Invalid Sheet/Table

Goal: Run SQL against data in an existing Excel worksheet.
I'm running the following code on an existing Excel worksheet. All ADO connections are working but when I run the SQL statement, it tells me that my table is invalid. Should I be passing the name of the worksheet OR the name of the table? I have tried both. Nothing works.
It errors when opening the recordset ("rs.Open strSQL, cn")
When I use the name of the worksheet in the SQL, I receive the following:
'AG1' is not a valid name. make sure that it does not include invalid characters or punctuation and that is is not too long.
When I use the name of the table, I receive the following:
The Microsoft Access database engine could not find the object 'Table4'. Make sure the object exists and that you spell it's name and the path name correctly. If 'Table4' is not a local object, check your network connection or contact the server administrator.
Thank you in advance.
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL As String
Dim strCon As String
' Declare variables
Dim strFile: strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
' "AG1" is the name of the sheet
' I've tried "Table4" (name of table) without luck
strSQL = "SELECT * FROM [AG1$] where [Language] = 'Spanish';"
' execute SQL query
rs.Open strSQL, cn
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub

Parameters in Excel External Data Union Query

I have two queries that pull data from SQL Server into Excel. Both work perfectly fine. I tried to Union them together and pass in a parameter as a date, and now nothing works. Here's a link to an article that describes how to use Microsoft Query, and pass in a parameter.
http://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/
All I want to do is get this working with a Union Query. Is that possible? Or, do I need a VBA solution to achieve this. I'm sure it's do-able, I just don't know exactly how to do it. I'd appreciate any suggestions.
Thanks!
Thanks everyone. I ended up doing it in VBA.
Sub ImportFromDB()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=SERVER_NAME;INITIAL CATALOG=Data_Base;"
'Use an integrated login.
strConn = strConn & "Trusted_Connection=Yes;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
Set sht = Worksheets("Impact Analysis")
With sht
.Range("N:U").ClearContents
.Range("N1").Resize(1, 8).Value = Array("CONTACT_ID", "CATEGORY", "COMPANY_CODE", "CUSTOMER_NO", "SECTOR", "DES", "ASOFDATE", "BALANCE")
Set rw = .Rows(2)
End With
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM MY_TABLE"
' Copy the records into cell A1 on Sheet1.
Worksheets("Impact Analysis").Range("N2").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

ADO Connection and Recordset with HTTP data source

I have the below Macro reading from a Database table stored as a txt file on the local C drive and returning an SQL query.
Public Function getData(fileName As String) As ADODB.Recordset
Dim cN As ADODB.Connection
Dim RS As ADODB.Recordset
Set cN = New ADODB.Connection
Set RS = New ADODB.Recordset
cN.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Cloud\;Persist
Security Info=False;Extended Properties=""text; HDR=Yes; FMT=Delimited;
IMEX=1;""")
RS.ActiveConnection = cN
RS.Source = "select top 10 * from " & fileName
Set getData = RS
End Function
I can then call the function and return data using the below, so far so good...
Sub Cloud()
Dim a As ADODB.Recordset
Set a = getData("file.txt")
a.Open
MsgBox (a.GetString())
a.Close
End Sub
BUT now I would like to move 'file.txt' from C:\Cloud\ to a HTTP location, ie http://it.wont.work/
How would I amend the above for this to work? I've searched and tested but nothing seems to work... I either get internet login failed or ISAM not found.
Many thanks

Excel VBA - Get Data from SQL based of Range - Automation Error

When running the below code I keep getting an Automation error, for the life of me I can't figure out why. Can anyone shed some light?
When I use the debug it highlights the below;
rs.Open SQLStr, cn
I saw some references to
I've been tasked to get data from a SQL DB based off the values in Column A Row 3 onwards.
Example of Excel Sheet:
ITEM | QTY TO PICK | QTY ON ORDER | Column 2 | Column 3 etc
PART 1 | 5 | <Data will be populated here>
PART 2 | 12 | <Data will be populated here>
This code runs through a Command Button.
The data pulled from SQL will be populated starting in C3 onwards.
Private Sub CommandButton2_Click()
' Create a connection object.
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "Provider=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "server=<server name>;INITIAL CATALOG=<DB Name>;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cn.Open strConn
'
'
ActiveSheet.Range("C3:G10000").Clear ' clear out existing data
Dim ItemNumber As String
ItemNumber = Range("A3").Value
' Create a recordset object.
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
SQLStr = "Select * from vw_WorksOrder WHERE ITEMNO = " & ItemNumber & ""
rs.Open SQLStr, cn
' Copy the records into cell A1 on Sheet1.
Sheet4.Range("C3").CopyFromRecordset rs
' Tidy up
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
As #Zac points out with incorrect use of quotes which resolves issue, consider not using quotes or variable concatenation at all by employing the industry best practice of parameterization. ADO can parameterize SQL calls using its Command CreateParameter method.
See below example using your setup where a ? is used as placeholder in prepared statement, then a parameter is later appended defining its name, type, direction size, and value.
...
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = cn
.CommandText = "SELECT * FROM vw_WorksOrder WHERE ITEMNO = ?"
.CommandType = adCmdText
.Parameters.Append cmd.CreateParameter("itemparam", adVarChar, adParamInput, 255, ItemNumber)
End With
Dim rs As New ADODB.Recordset
Set rst = cmd.Execute
...
Also, another industry best practice is error and exception handling for runtime errors as AutomationError is not useful for debugging. And you want to release all Set objects regardless of error or not. In VBA, you can use the On Error handling to output more useful messages and release objects from memory accordingly.
Private Sub CommandButton2_Click()
On Error Goto ErrHandle
'...same code but without any Set obj = Nothing (since used in ExitHandle)
ExitHandle:
Set rs = Nothing
Set cmd = Nothing
Set cn = Nothing
Exit Sub
ErrHandle:
Msgbox Err.Number & " - " & Err.Description
Resume ExitHandle
End Sub

runtime error '-2147217900' (80040e14)': automation error using where in the sql query from excel vba

I am trying to connect to my sqlserver express 2005 from excel vba using the following (copied from some forum routine as i am not very into databases). It works perfect. As soon as I use WHERE in the sqlquery variable (already verified quotes double and single) i get
runtime error '-2147217900' (80040e14)':
automation error
Similar routine that work pulling data from other people same thing. I appreciate deeply your help
Thanks
Sub ConnectTEST()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim sqlquery As String
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
sqlquery = "SELECT * FROM [Logisuite].[dbo].[EoWebStatus]"
'Connect to the Pubs database on the local server.
strConn = strConn & "Server=SERVITRANSMAIn\SQLEXPRESS;Database=logisuite;Trusted_Connection=True;"
'Use an integrated login.
strConn = strConn & "INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open sqlquery
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub