I have a VBA code below, but every time when I try to execute the VBA code it gives me error on [Dlookup]
I spent hours and hours trying to get the Dlookup right, but no luck.
Appreciate if you can have a look of it and provide me with some insights or solutions. Thanks.
Sub Quality()
Dim Sql As String
StrDate = InputBox("YYYY/MM/DD")
Sql = "Insert Into Roster_QC Select dbo_Recipients.[UniqueID] AS [UID],
DLookUp("[Address1]", "dbo_NamesAndAddresses", "[PersonID]=' " & [UID] & " ' AND [PrimaryAddress]=1" ) AS [Address]…FROM…
WHERE…ORDER BY
CurrentDb.Execute Sql
DoCmd.OpenReport "RosterQC_Report", View:=acViewPreview
End Sub
Also, I have changed the Dlookup as of below
DLookUp(""[Address1]"", ""dbo_NamesAndAddresses"", ""[PersonID]='" & [UID] & "' AND [PrimaryAddress]=1"" ) AS Address
This give rise to error - [UID] External Name not defined.
Thanks #June7, joining dbo_Recipients and dbo_NamesAndAddresses fixed my problem.
Related
I have the below VBA to extract data from the database:
Sub Get_Data_from_DWH ()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=XX.XXX.XXX.XX; DATABASE=bi; UID=testuser; PWD=test; OPTION=3"
conn.Open
strSQL = " SELECT" & _
" product, brand, sales_channel," & _
" country, sales_manager, sales_date, return_date, " & _
" process_type, sale_quantity, return_quantity " & _
" FROM bi.sales" & _
" WHERE sales_date BETWEEN '2020-01-01' AND '2020-06-30' " & _
" AND country IN ('DE', 'US', 'NL') " & _
" ORDER BY FIELD (brand, 'brand_A', 'brand_B', 'brand_C');"
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
This VBA extracts the data based on the SQL without any problem.
However, in my original file the VBA is much bigger and therefore I have to use a lot of new line separators " and " & _ .
This makes the handling of the SQL within the VBA very difficult since the structure is quite confusing.
Therefore I am wondering if there is an alternative that allows you to enter the SQL without the new line separators.
Something like this:
strSQL = " SELECT
product, brand, sales_channel,
country, sales_manager, sales_date, return_date,
process_type, sale_quantity, return_quantity
FROM bi.sales
WHERE sales_date BETWEEN '2020-01-01' AND '2020-06-30'
AND country IN ('DE', 'US', 'NL')
ORDER BY FIELD (brand, 'brand_A', 'brand_B', 'brand_C'); "
Do you have any idea if this is possible?
Definitive answer - It's not possible in VBA, there's no way for the IDE to allow line breaks in a string.
But here's some suggestions:
If you can't create views on the database and just use those, maybe you could directly link to the data source and do queries that way? So you don't have to use VBA to write queries - Excel has great in-built connectivity and you get a MySQL library, just google "connect to mysql database in excel"
If you really want your queries defined as text somewhere else, one thing that might help to neaten your code is to load your strings from another place where you can keep your sql queries in a format you prefer.
You could load them from a VBA module, which would still have split strings but you can call them like StringSQL = Module1.GetQueryOne and it helps keep the execution code and the SQL strings separate
You could create a method to pull queries from worksheet cells, or maybe keep them in textboxes on a worksheet, then you can use
SqlString = ThisWorkbook.Sheets("Sheet1").Shapes("SqlQuery1").OLEFormat.Object.Text
or even keep them in a text file that accompanies your Excel workbook and load them from there.
Thanks in advance everyone, Im using vba and MS Access 2016 to work on a restaurant's db.
I need to open a table to get a record which is a table name that I then need to open, its kinda messy but I thought I had it until I started getting the 3078 error. (Btw I just started using access for this project so it could be a simple syntax error I don't see)
The db im working on was made in a half assed way unfortunately so it isn't quietly consistent or well formated and it is half in spanish half in english however I'm sure the table name is correct and exists. If I put the query in access instead of vba and with the name instead of a variable it works just fine. Here's the code.
Sub QRventas()
Dim ventas As DAO.Recordset
Dim qrv As String
'Query daily sales
qrv = (SELECT menus.id, menus.descripcion, Sum(Nz(ComandasD.cantidad)) AS Total FROM ~~long and ugly but working query)
Set ventas = CurrentDb.OpenRecordset(qrv)
Dim receta As DAO.Recordset
Dim qrr As String
Do While Not ventas.EOF
'QR recipes
ventas.MoveNext
qrr = "SELECT ID, Ingredientes, Cantidad FROM [" & ventas(1) & "] GROUP BY ID, Ingredientes, Cantidad;" '<- Error Here
Set receta = CurrentDb.OpenRecordset(qrr) '<- Complains here 3078
Do While Not receta.EOF
'Updating Storage
CurrentDb.Execute "UPDATE Almacen " _
& "SET Cantidad_almacenada = Cantidad_almacenada - (cantidad * Total) " _
& "WHERE ID = " & receta(1) & ";"
receta.MoveNext
Loop
Loop
End Sub
possibly 'Fields' is missing:
qrr = "SELECT ID, Ingredientes, Cantidad FROM [" & ventas.Fields(1) & "]...
If Access complains that the table isn't there, it isn't.
Or, specifically use the Value property of the field.
So insert a debug line and study which table name it was supposed to find:
'QR recipes
ventas.MoveNext
Debug.Print "[" & ventas(1) & "]"
qrr = "SELECT ID, Ingredientes, Cantidad FROM [" & ventas(1).Value & "] GROUP BY ID, Ingredientes, Cantidad;" '<- Error Here
I tried the answers that people posted here but had no luck with them, then I did a "Compact and Repair" and the issue went away...
Thanks everyone again.
I'm trying to setup reminders based on tasks added from a Table called "Tasks" Here is the code I'm using but something isn't right as it keeps giving me issues with the following line:
intStore = DCount("[TaskName]", "[Status]", "[DueDate] <=Now() AND [Complete] =0")
When the code runs I get the error:
Microsoft Access database engine cannot find the input table or query
for 'Status' Make sure it exists and is spelled correctly.
In my table I have fields for Task Name, Status, and Due Date so I'm not exactly sure why this is coming up.
Below is the entire line of code:
Private Sub Form_Load()
'On Load of the switchboard check Jobs table for any uncompleted jobs
Dim intStore As Integer
intStore = DCount("[Priority]", "[Tasks]", "[DueDate] <=Now() AND [PercentComplete] <=0")
If intStore = 0 Then
Exit Sub
Else
If MsgBox("There are " & intStore & " uncompleted jobs" & _
vbCrLf & vbCrLf & "Would you like to see these now?", _
vbYesNo, "You Have Uncomplete Jobs...") = vbYes Then
DoCmd.Minimize
DoCmd.OpenForm "Tasks", acNormal
Else
Exit Sub
End If
End If
End Sub
You can only perform a DCount on one field (primary key is best if you are just doing a general count on the table). You have entered "[Status]" where Access is expecting a table or query name to be used as the source of the [TaskName] field.
See here for more information.
Judging by your other code example I expect that your code needs to be:
intStore = DCount("[TaskName]", "[Tasks]", "[DueDate] <=Now() AND [Complete] =0")
I'm using Access 2007 by itself with no connections to SQLserver or anything for this process.
I want to take the result of a few DateDiff functions and use an Update SQL statement to put them into fields on a table. My table's fields are number fields, and I am under the impression that DateDiff returns a number.
I try this, but I get a data type mismatch error on the first DateDiff (Pause1). I tried taking the quotes off of the fields but then I get a different error (can't find the field '|' referred to in your expression).
Here is my code. It really starts at the comment TIME REPORTING CODE HERE:
Private Sub StopNextButton_Click()
'
GetID = Forms!frm_MainMenu!AssocIDBox
CurRecord = Forms!frm_EC_L1_L2![L#].Value
'
DoCmd.RunSQL "UPDATE tbl_Data SET tbl_Data.[tsEndAll] = Now WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'TIME REPORTING CODE HERE'
'
Pause1 = DateDiff("s", "[tsPause1]", "[tsResume1]")
Pause2 = DateDiff("s", "[tsPause2]", "[tsResume2]")
ECTime = (DateDiff("s", "[tsECStart]", "[tsUpdated]") - (Pause1 + Pause2))
LTime = DateDiff("s", "[tsStartAll]", "[tsEndAll]")
'
DoCmd.RunSQL "UPDATE tbl_Data SET [ECTime] = " & ECTime & ", [LoanTime] = " & LTime & " WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'END OF TIME REPORTING CODE'
'
DoCmd.GoToRecord , , acNext
'
ETC.
Based off of your comment I assume that those fields are on the record your form is currently 'viewing'. If so you can just refer to them as Me.tsPause1 without [] or quotes. Pretty sure you can also do just tsPause1 but I find Me.tsPause1 makes it more obvious what you are doing.
However I think you are updating the field you are currently viewing and then immediately trying to access those updated fields. I am fairly certain you will need to a Me.Refresh before those fields' new values are accessible. Hopefully someone with more specific experience will correct me if I am wrong. I think something like this should work for you:
Me.Refresh
Pause1 = DateDiff("s", Me.tsPause1, Me.tsResume1)
Pause2 = DateDiff("s", Me.tsPause2, Me.tsResume2)
ECTime = (DateDiff("s", Me.tsECStart, Me.tsUpdated) - (Pause1 + Pause2))
LTime = DateDiff("s", Me.tsStartAll, Me.tsEndAll)
I'm using a MS Access database linked with a Sharepoint Server. MS Access Forms as FrontEnd and Sharepoint Lists as BackEnd.
Today i can see all the informations from the lists using access forms, without problems.
What i need:
I'm trying to insert new registers on the list, using a SQL command: "INSERT INTO..."
if there is another possibility to insert the record in the list, may be useful
What's happening?
When i call the DoCmd.RunSQL(txtsql), i receive a runtime error 3999 saying i'm disconnected from the server.
My code now:
I tried using recordsets, but didn't succeed.
I need to run this SQL many times, changing the string "txtSql" inside a loop. Like this:
Dim MaxSonda As Integer
'Get the max ID from the list
MaxSonda = Nz(DMax("IdSonda", "Sondas", "((Sondas.[Tipo Sonda])<>1 Or (Sondas.[Tipo Sonda]) Is Null)"), 0)
MsgBox "MaxSonda = " & MaxSonda
'Run the code for each "sonda"
Do While MaxSonda > 1
If Nz(DLookup("[Tipo Sonda]", "Sondas", "Sondas!IdSonda = " & MaxSonda), 1) <> 1 Then
DoCmd.OpenTable "Resumo", acViewNormal, acAdd
DoCmd.GoToRecord acDataTable, "Resumo", acNewRec
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) SELECT #" & LastData + 1 & "#, " & MaxSonda & ", 0;"
MsgBox txtSql
DoCmd.RunSQL txtSql
DoCmd.Close acTable, "Resumo", acSaveYes
End If
MaxSonda = MaxSonda - 1
Loop
P.S.: The MsgBox is just for check the steps
thanks for help
You don't need to open the list/table to insert a record. I don't know why you are using loop to insert rows but if that is your intention try this SQL_COMMAND within your loop:
If Nz(DLookup("[Tipo Sonda]", "Sondas", "[IdSonda] = " & MaxSonda), 1) <> 1 Then
txtSql = "INSERT INTO Resumo ( Data, Sonda, Status ) VALUES ('" & LastData + 1 & "'," & MaxSonda & ",0);"
MsgBox txtSql
DoCmd.RunSQL txtSql
End If
also note #tags are used to insert dates in Access, if you are intend to save dates save them in international format as strings like
vba.Format$([date_field],"yyyy-mm-dd hh:mm:ss")
this way you can just save as string without using the #tags.
Maybe this could help somebody. I did have the same problem and i solved it removing the sharepoint list from access and add it again. Take a seconds to make a sql query but it works.
greet