Automation Error when executing SQL Server Script in Excel VBA - sql-server

I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute

Related

Pass Array Into Subroutine for Excel VBA?

I'm trying to pass the results of an array into a subroutine. I have an array that picks up four different Buyer codes from a list. They're labelled as BuyOne, BuyTwo, BuyThree, BuyFour. I'm trying to get the results into the next subroutine, but I'm getting a type mismatch at the subroutine call. Even when I fiddle with it I don't know how to get the results into the subroutine. Can anyone tell me what i'm doing wrong?
Code below:
lastRow = Range("O" & Rows.Count).End(xlUp).Row
Set rBuyerList = Range("O1:O" & lastRow)
arrBuyer = Array("BuyOne", "BuyTwo", "BuyThree", "BuyFour")
For i = 0 To UBound(arrBuyer)
With Application
chkFind = .IfError(.Match(Range(arrBuyer(i)), Range("O1:O50"), 0), 0)
End With
If Range(arrBuyer(i)) = vbNullString Or chkFind = False Then
MsgBox "Invalid Buyer Code.." & arrBuyer(i)
Range(arrBuyer(i)).Select
End If
Next i
Call runFinished(sFrDt, sToDt, arrBuyer())
Sheets("Main Sheet").Select
MsgBox ("done...")
End Sub
Sub runFinished(sFrDt As String, sToDt As String, arrBuyer() As Variant)
Dim SQL As String
' add a new work sheet
ActiveWorkbook.Worksheets.Add
' dispay Criteria
Cells(1, 1) = "Run Date: " & Now()
Call MergeLeft("A1:B1")
Cells(2, 1) = "Criteria:"
Cells(2, 2) = "From " & Range("reqFrDT") & " -To- " & Range("reqToDt")
' SQL
SQL = "select a.StockCode [Finished Part], a.QtyToMake, FQOH,FQOO,/*FQIT,*/FQOA, b.Component [Base Material], CQOH,CQOO,CQIT,CQOA " & _
"from ( " & _
" SELECT StockCode, sum(QtyToMake) QtyToMake " & _
" from [MrpSugJobMaster] " & _
" WHERE 1 = 1 " & _
" AND JobStartDate >= '" & sFrDt & "' " & _
" AND JobStartDate <= '" & sToDt & "' " & _
" AND JobClassification = 'OUTS' " & _
" AND ReqPlnFlag <> 'I' AND Source <> 'E' Group BY StockCode " & _
" ) a " & _
"LEFT JOIN BomStructure b on a.StockCode = b.ParentPart " & _
"LEFT JOIN ( " & _
" select StockCode, sum(QtyOnHand) FQOH, Sum(QtyAllocated) FQOO, Sum(QtyInTransit) FQIT, Sum(QtyOnOrder) FQOA " & _
" from InvWarehouse " & _
" where Warehouse in ('01','DS','RM') " & _
" group by StockCode " & _
") c on a.StockCode = c.StockCode " & _
"LEFT JOIN ( " & _
" select StockCode, sum(QtyOnHand) CQOH, Sum(QtyAllocated) CQOO, Sum(QtyInTransit) CQIT, Sum(QtyOnOrder) CQOA " & _
" from InvWarehouse " & _
" where Warehouse in ('01','DS','RM') " & _
" group by StockCode " & _
") d on b.Component = d.StockCode "
SQL = SQL & _
"LEFT JOIN InvMaster e on a.StockCode = e.StockCode " & _
"WHERE 1 = 1 " & _
"and e.Buyer in ('" & BuyOne & "','" & BuyTwo & "','" & BuyThree & "','" & BuyFour & "') " & _
"ORDER BY a.StockCode "
If you have this line in your code
arrBuyer = Array("BuyOne", "BuyTwo", "BuyThree", "BuyFour")
Proper call should be
Call runFinished(sFrDt, sToDt, arrBuyer)
And proper declaration of the function is
Sub runFinished(sFrDt As String, sToDt As String, arrBuyer As Variant) without ()
Edit (Thanks to #Rory)
Previously stated is true if arrBuyer was not declared as follows: dim arrBuyer() as variant or dim arrBuyer(). On the other hand if declaration was dim arrBuyer() 'as variant OP's code would work w/o any changes.
Final note: I still prefer not using arrBuyer() As Variant in the sub declaration.

Join Excel-Table with SQL Server

My excel-sheet is connected with the data of the sql-server. My clients shall be able to write some columns back to the sql server. The excel-filenames are variable, but the sheeetname and the columns are always static. I tried it with a button and vba but it ends up in error:
Syntaxerror (missing operator) in queryexpression 'UPDATE hbs SET lieferinfo_prio_neu = xlsx.liefer_prio_neu FROM [Provider=SQLOLEDB;Data Source=myserver;Database=mydb;UID=myuser;PWD=mypass;].[tbl_haka_base_size] hbs JOIN [Tabelle3$] xlsx ON xlsx.Artikelnummer'
The internal excel-sheetname is 'Tabelle3', the custom-name is 'Hakabase':
I tried both names without any result.
My code:
Dim excelConn As String
Dim sqlServerConn As String
Dim sqlCommand As String
Dim conn As ADODB.Connection
excelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& ThisWorkbook.FullName _
& ";Extended Properties=""Excel 12.0 Xml;HDR=Yes;IMEX=1"";"
sqlServerConn = "[Provider=SQLOLEDB;" _
& "Data Source=myserver;" _
& "Database=mydb;" _
& "UID=ymuser;PWD=mypass;]"
sqlCommand = "UPDATE hbs " _
& " SET lieferinfo_prio_neu = xlsx.liefer_prio_neu " _
& " FROM " & sqlServerConn & ".[tbl_haka_base_size] hbs " _
& " JOIN [Tabelle3$] xlsx " _
& " ON xlsx.Artikelnummer=hbs.artikelnummer"
Set conn = New ADODB.Connection
conn.Open excelConn
conn.Execute sqlCommand
I've also tried to connect to the sqlserver + join the excel-data via openrowset but the server disallowed that:
& " JOIN OPENROWSET('MSDASQL', " _
& " 'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" _
& ThisWorkbook.FullName & "', 'SELECT * FROM [Tabelle3$]') xlsx" _
Installable ISAM not found
I think I have to create a linked server for each file and enable 'InProcess' for those files. This is not possible because the files are variable.
I've found an alternative solution which is a little bit slow so I still hope someone else is able to answer my question.
The alternative solution is to iterate through each row.. The file got about 150.000 rows and just for 10.000 rows I am waiting about 10 minutes..
Here is the part of iterating
For Each range In sheet.rows: Do
'Continue on headline
If range.Row = 1 Or range.EntireRow.Hidden = True Then
Exit Do
End If
If Len(sheet.Cells(range.Row, lieferInfoColumnIndex)) > 0 Then
articleNumber = sheet.Cells(range.Row, artNoColumnIndex)
UpdateDatabase (articleNumber)
savings = savings + 1
End If
Loop While False: Next range
Here is the slow update function for each row:
Private Sub UpdateDatabase(articleNumber As String)
Dim sqlServerConn As String
Dim sqlCommand As String
Dim conn As ADODB.Connection
sqlServerConn = "Provider=SQLOLEDB;" _
& "Data Source=myserver;" _
& "Database=mydb;" _
& "UID=myuser;PWD=mypass;"
sqlCommand = "UPDATE hbs " _
& "SET lieferinfo_prio_neu=NULL " _
& "FROM [TBL_HAKA_BASE] hbs " _
& "WHERE Artikelnummer=" + articleNumber
Set conn = New ADODB.Connection
conn.Open sqlServerConn
conn.Execute sqlCommand
End Sub

How to fix error "SQLexception was unhandled by user code incorrect syntax near 'FROM'

Anyone can help me on where the 'FROM' error is would be greatly
Here my code vb is problem
Imports System.Data
Imports System.Data.SqlClient
Private Sub ButtonOK_Click() Handles ButtonOK.Click
sql = "SELECT Drug.DrugID, Drug.DrugName, Categories.CategoryName, " & _
"Suppliers.CompanyName, Drug.UnitPrice, Drug.UnitsInstock, " & _
"FROM Drug " & _
"LEFT JOIN Categories " & _
"ON (Drug.CategoryID = Categories.CategoryID) " & _
"LEFT JOIN Suppliers " & _
"ON (Drug.SupplierID = Suppliers.SupplierID) " & _
"WHERE Drug.ExpireDate BETWEEN #dt1 AND #dt2"
command = New SqlCommand(sql, connection)
Dim dt1 As String = GetDateTime(DateTimePicker1)
Dim dt2 As String = GetDateTime(DateTimePicker2)
command.Parameters.AddWithValue("dt1", dt1)
command.Parameters.AddWithValue("dt2", dt2)
adapter = New SqlDataAdapter(command)
dataSt = New DataSet()
adapter.Fill(dataSt, "expire")
DataGridView1.DataSource = dataSt.Tables("expire")
DataGridView1.RowsDefaultCellStyle.BackColor = Color.White
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = _
Color.PowderBlue
For i = 0 To headerText.Length - 1
DataGridView1.Columns(i).HeaderText = headerText(i)
Next
ButtonToExcel.Enabled = True
End Sub
Here's the error:
Incorrect syntax near the keyword 'FROM'.
This may work, Just remove the extra ',' from the end of second line.
sql = "SELECT Drug.DrugID, Drug.DrugName, Categories.CategoryName, " & _
"Suppliers.CompanyName, Drug.UnitPrice, Drug.UnitsInstock " & _
"FROM Drug " & _
"LEFT JOIN Categories " & _
"ON (Drug.CategoryID = Categories.CategoryID) " & _
"LEFT JOIN Suppliers " & _
"ON (Drug.SupplierID = Suppliers.SupplierID) " & _
"WHERE Drug.ExpireDate BETWEEN #dt1 AND #dt2"

Run-time error 3061 Too few Parameters. Expected 2

Can someone please let me know what is wrong with this code? I have checked all lines for misspellings - this isnt the issue. All tables and queries are written as they exist in the db. Any help is appreciated.
Private Sub LoadArray()
'---------------------------
'---------------------------
'This procedure loads text into the 3rd column of the array
'---------------------------
'---------------------------
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsFiltered As DAO.Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "SELECT tblProperties.Name, tbl1OpportuniyType.Type, qryPropertiesALLTypesALLTbls.TotalUnits, " _
& "qryPropertiesALLTypesALLTbls.EventStartTimeEachDay, qryPropertiesALLTypesALLTbls.EventEndTimeEachDay, " _
& "qryPropertiesALLTypesALLTbls.EventStartDate, qryPropertiesALLTypesALLTbls.EventStopDate, " _
& "qryPropertiesALLTypesALLTbls.TechOpsGroup, qryPropertiesALLTypesALLTbls.TechOpsResource " _
& "FROM tbl1OpportuniyType RIGHT JOIN (qryPropertiesALLTypesALLTbls INNER JOIN tblProperties ON qryPropertiesALLTypesALLTbls.[PropertyComplex_ID] = tblProperties.[PropertyComplex_ID]) ON tbl1OpportuniyType.[OpportunityType_ID] = tblProperties.OpportunityType " _
& "WHERE (((qryPropertiesALLTypesALLTbls.EventStartDate) Is Not Null));"
'Debug.Print strSQL
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
'This line ensures that the recordset is populated
If Not rs.BOF And Not rs.EOF Then
'Loops through the Array using dates for the filter
For i = LBound(myArray) To UBound(myArray)
If myArray(i, 1) Then
'Filters recordset with array dates
rs.Filter = "[EventStartDate]= " & myArray(i, 0)
'Open up new recordset based on filter
Set rsFiltered = rs.OpenRecordset
'Loop through new recordset
Do While (Not rsFiltered.EOF)
'Adds text to the 3rd column of the array
myArray(i, 2) = myArray(i, 2) & vbNewLine _
& rsFiltered!Type & " - " & vbNewLine _
& rsFiltered!Name & " " _
& rsFiltered!EventStartDate & " - " _
& rsFiltered!EventStopDate & " " _
& rsFiltered!EventStartTimeEachDay & " - " _
& rsFiltered!TechOpsGroup & " " _
& rsFiltered!TechOpsResource & " " _
& vbNewLine
rsFiltered.MoveNext
Loop
End If
Next i
End If
rsFiltered.Close
rs.Close
'Sets objects to nothing
Set rsFiltered = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
It isn't clear where myArray comes from, but the filter needs an adjustment to convert the date value to a string expression:
rs.Filter = "[EventStartDate] = #" & Format(myArray(i, 0), "yyyy\/mm\/dd") & "#"

VBA Contains Function

I'm currently making an Excel function that connects to an SQL server and retrieves data as long as it matches the given criteria.
Public Function VehModelUnitsCount(VehModel As String, fran As String, Site As Integer, SaleType As String, StartDate, EndDate, New As Integer) As Variant
Application.Volatile
If adoCN Is Nothing Then Call SetUpConnection
Set adoRS = New ADODB.Recordset
EvoStartDate = Format(StartDate, "yyyy/mm/dd")
EvoEndDate = Format(EndDate, "yyyy/mm/dd")
strSQL = "SELECT COUNT(*) As RCOUNT FROM CARTYPES RIGHT OUTER JOIN CARS ON CARTYPES.Description = CARS.Type LEFT OUTER JOIN CARS2 ON CARS.[Stock Number] = CARS2.[Stock Number]" & Chr(13)
strSQL = strSQL & "WHERE (CARTYPES.NewSale = " & New & " )" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Franchise = '" & fran & "')" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Site = " & Site & ")" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.SaleTypeDesc = '" & SaleType & "')" & Chr(13)
strSQL = strSQL & "AND (CARS2.InvoiceDate BETWEEN '" & StartDate & "' AND '" & EndDate & "')" & Chr(13)
strSQL = strSQL & "AND (CARS.Invoiced = '1')" & Chr(13)
Rem strSQL = strSQL & "AND (CARS.Model = '" & VehModel & "')" & Chr(13)
[THIS ONE] - strSQL = strSQL & "AND (CARS.Model CONTAINS '" & VehModel & "')" & Chr(13)
adoRS.Open strSQL, adoCN, adOpenForwardOnly, adLockReadOnly
VehModelUnitsCount = adoRS.Fields("RCOUNT").Value
adoRS.Close
End Function
The string marked with [THIS ONE] is the one I am struggling with, I need to find out whether or not the cell contains the given string, but apparently using 'CONTAINS' doesn't work.
Any help on completing this would be amazing.
Thank you.
You could try -
strSQL = strSQL & "AND (CARS.Model LIKE '%" & VehModel & "%')" & Chr(13)

Resources