Excel VBA SQL multiple where condition - excel

I need help fixing my conditions. I have 3 columns (Case #, Analyst & Status). I need to display a certain Analyst plus all status that aren't closed.
Dim c As String
Dim use As String
use = LabelUser.Caption
c = "Closed"
SQL = "SELECT * FROM tbl_Raw WHERE Analyst = '" & use & "' OR Status <> '" & c & "'"
this statement displays all cases under the analyst, including closed (c).
I tried this but it displays nothing.
SQL = "SELECT * FROM tbl_Raw WHERE Analyst = '" & use & "' AND Status <> '" & c & "'"

It's been a long time since this question has been made, however, it still worth answering.
Whenever you use SQL statement within ADO connection, you must assign brackets around and dollar sign at the end of the Table's name. E.g: "SELECT * FROM [tbl_Raw$] WHERE Analyst = '" & use & "' OR Status <> '" & c & "'"

Related

Select rows based on the values in a column

I have an Excel file with a userform where users can insert exchange rates and different parameters for financial report.
I set up a DB file and I want to select rows based on the values in BV column (book value) and it should be higher than 100.000EUR.
The problem is that I have three other currencies besides EUR and I need to calculate EUR amount based on exchange rate.
I made an exchange rate field in my userform (BVAL is EUR default, and I also have BVGBP, BVPLN and BVRSD, which are 100.000EUR divided by each exchange rate).
This works:
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency = 'EUR')";"
But when I try to combine multiple results, syntax is not working. I tried other solutions found online.
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency='EUR') or (bv>=" & BVGBP & " and Currency='GBP') _
or (bv>=" & BVPLN & " and Currency='PLN') or (bv>=" & BVRSD & " and Currency='RSD');"
You SQL syntax is correct, but your VBA is not. Also, for better readability, break up the long lines:
SqlQuery = " SELECT * FROM Sheet1 where " & _
"(bv>=" & BVAL & " and Currency='EUR') or " & _
"(bv>=" & BVGBP & " and Currency='GBP') or " & _
"(bv>=" & BVPLN & " and Currency='PLN') or " & _
"(bv>=" & BVRSD & " and Currency='RSD');"

Easier way to use declared Strings in Query in VBA

I'm writing a macro which should run queries to transfer data from excel to a Access database, and everything is working fine, however, if I want to use a String in one of these queries, I've to type them like this:
'" & Lijn & "'
I know that the following code (which is written in VBA) is way easier to write in Javascript, by using question marks and setString:
VBA:
Dim ShiftsQ As String
ShiftsQ = "INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES ('" & Lijn & "', '" & Operator & "', '" & Ploeg & "', '" & Teamleider & "');"
Javascript:
var ShiftsQ = SQL.prepareStatement(INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES (?, ?, ?, ?);
ShiftsQ.setString(1, Lijn);
ShiftsQ.setString(2, Operator);
ShiftsQ.setString(3, Ploeg);
ShiftsQ.setString(4, Teamleider);
Is there anyway to write the VBA code like the Javascript one?
As far as I know, there is nothing like the .NET string.Format() method VBA. But you could write your own version of such a function that uses deputys and returns a formatted string.
Private Sub Main()
' Your actual query
' The deputys are indexed in curley brackets (inspired from the .NET syntax of the equivalent function, making your code easy to read for .NET programmers)
Dim qry As String
qry = "SELECT {0}, {1} FROM {2} WHERE {3}"
' The values to set for the deputys in your query
Dim parameters(3) As String
parameters(0) = "firstname"
parameters(1) = "lastname"
parameters(2) = "users"
parameters(3) = "userID = 'M463'"
' For demo purposes, this will display the query in a message box
' Instead of the MsgBox, you would use the formatted query to execute against the database
MsgBox FormatString(qry, parameters)
End Sub
' This is where the magic happens, the deputys in the given string will be replaced with the actual values from the provided array
Private Function FormatString(strInput As String, paramValues() As String)
' This will be our return value
Dim strOutput As String
strOutput = strInput
' Verify that the given count of parameters matches the given count of deputys in the input string
Dim maxParamIndex As Integer
maxParamIndex = UBound(paramValues)
Dim deputyCount As Integer
For i = 1 To Len(strOutput) + 1 Step 1
If Mid(strOutput, i, 3) = "{" & deputyCount & "}" Then
deputyCount = deputyCount + 1
End If
Next
' If there is a mismatch between the count of parameters and the count of deputys, display exception message and exit the function
' Adding +1 to maxParamIndex is neccessary, as maxParamIndex refers to the maximum index (starting at 0, not 1) of the given array and deputyCount refers to the actual count of deputys (starting at 1)
If maxParamIndex + 1 <> deputyCount Then
MsgBox "Number of deputys has to match number of parameters for the given string:" & vbCrLf & strInput, vbCritical, "Exception in Function FormatString"
FormatString = ""
End If
' Iterate through the array and replace the deputys with the given values
For i = 0 To maxParamIndex Step 1
strOutput = Replace(strOutput, "{" & i & "}", paramValues(i))
Next
' return the formatted string
FormatString = strOutput
End Function
Result of example:
If I face this problem I would simply solve it on my own (althoug there might be other "standard" solutions), by defining my own simple, global function (put in in any standard code module)
Public Function S_(str as String) as String
S_ = chr(39) & str & chr(39)
End Function
ShiftsQ = "INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES (" & S_(Lijn) & ", " & S_(Operator) & ", " & S_(Ploeg) & ", " & S_(Teamleider) & ");"
This way, I will follow a simple and systematic rule in all my project, that is call S_(param) on any parameter of text type in my queries...

Querying data between a specific date and time in VBA

I have a database in access where every data has a date and time in two different columns.
I need to to run a query in excel using VBA which would fetch me data between two specific dates and times (eg: 01/05/2016 13:15 and 03/05/2016 10:11)
My query is as follows:
SQL = "SELECT * FROM " & database & " WHERE symbol='" & companyName & _
"' AND AdmitDate BETWEEN " & (fromDate + fromTime) & " AND " & (toDate + toTime) & ""
However, it gives me a syntax error which says:
'Missing operator in query expression'
I am not able to figure out where I have gone wrong.
Please help!
You need the right string expressions for the date/time values. Format can create these:
SQL = "SELECT * FROM " & database & " WHERE symbol='" & companyName & "' AND AdmitDate BETWEEN #" & Format(fromDate + fromTime, "yyyy\/mm\/dd hh\:nn\:ss") & "# AND #" & Format(toDate + toTime, "yyyy\/mm\/dd hh\:nn\:ss") & "#"

Lotus notes: change view selection formula by script

I'm trying to change view selection formula by script with this selection formula:
formula = "SELECT (#Modified = [" & Left(doc1.LastModified,10) & "]) & form = ["& Cstr(doc1.form(0)) &"]"
But when I try to execute it Notes retrive me the following error:
Notes error: Unknown [KeyWord] for #Function (SELECT (#Modified = [03/02/2015]) & form=[myform])
You should use quotes for form instead of square brackets.
Here is example:
formula$ = {SELECT (#Modified = [} & Left(doc1.LastModified,10) & {]) & form = "} & doc1.form(0) & {"}
Which generate this string:
SELECT (#Modified = [03/02/2015]) & form = "myform"

Can I make my VBScript program ignore a field when reading from Excel?

I did a little bit of reading on what I am about to ask, but I couldn't find a specific answer.
I am writing a program in VBScript that will read an excel file and then update an Access Database.
It works great, but the problem I can foresee running into is thus:
What happens when the excel file has a blank on a specified field? I don't want the script file to update a "blank" to the database, I want it to be left unchanged in the database ONLY if there is a blank in the excel file. If not, proceed as normal.
Currently, it will read this as a blank and insert the blank into the row in my database.
Is this possible? For the script to basically ignore fields it reads (in Excel) that are blank while only updating (in the database) the fields that actually have data (in Excel) in them?
Currently, it says no in the field in the database. This is just a brief code example. In the Excel sheet, it says yes in the correct column.
Do Until objExcel.Cells(intRow,1).Value = ""
asset_Tag = objExcel.Cells(intRow, 1).Value
ebay = objExcel.Cells(intRow, 2).Value
intRow = intRow + 1
objRecordSet.Open "UPDATE Test SET Listed_Ebay = '" & ebay & "' WHERE Asset_Tag = '" & asset_Tag & "'", _
objConnection
Loop
If you are reluctant to add 20 If statements to your code, surely you could put Excel's native COUNTA functionality to make sure that there are 20 values before the update operation.
With objExcel
Do Until .Cells(intRow,1).Value = ""
If .Application.CountA(.Cells(intRow, 1).Resize(1, 20)) = 20 Then
asset_Tag = .Cells(intRow, 1).Value
ebay = .Cells(intRow, 2).Value
objRecordSet.Open "UPDATE Test SET Listed_Ebay = '" & ebay & "' WHERE Asset_Tag = '" & asset_Tag & "'", objConnection
End if
intRow = intRow + 1
Loop
End With
I had a guess a bit as to which 20 values were intended to be filled but I think you can get the idea.
EDIT NOTEĀ¹: reordered the code lines to maintain the intRow according to the loop.
EDIT NOTEĀ²: You may want to conditionally pass the original value back into the UPDATE query if the LEN of the new value is zero.
Dim qry as String
qry = "UPDATE Test SET " & _
"Listed_Ebay = Iif(CBool(Len('" & ebay & "')), '" & ebay & "', Listed_Ebay), " & _
"Listed_Amazon = Iif(CBool(Len('" & amzon& "')), '" & amzon & "', Listed_Amazon), " & _
"Listed_POS = Iif(CBool(Len('" & pos& "')), '" & pos & "', Listed_POS) " & _
"WHERE Asset_Tag = '" & asset_Tag & "'"
objRecordSet.Open qry, objConnection
I'm just making stuff up past the original one field example you provided but you should be able to transcribe this for your own 8 fields. I'm using LEN here on text values but comparing numbers to zero (or even their LEN would be appropriate.

Resources