how to convert query to vb code (1 Viewer)

sandanet

Registered User.
Local time
Yesterday, 18:17
Joined
Oct 14, 2017
Messages
40
Hello everybody, :)

I'm looking for your help to convert query to vb code:confused:, please kindly look at the attached database.

Thank you in advance,
 

Attachments

  • example.zip
    12.5 KB · Views: 175

Ranman256

Well-known member
Local time
Yesterday, 21:17
Joined
Apr 9, 2015
Messages
4,337
you shouldnt, queries are better.
but,
in the query, click the design,SQL button
copy sql
put in vb code
sql = "select * from table"
 

sandanet

Registered User.
Local time
Yesterday, 18:17
Joined
Oct 14, 2017
Messages
40
you shouldnt, queries are better.
but,
in the query, click the design,SQL button
copy sql
put in vb code
sql = "select * from table"

thank you for replay, when i do that i get error when i copy this sql code

Code:
sql = "SELECT Format(Int((108120-[Value])/3600),"00") AS Total FROM tbl1 WHERE (((tbl1.Property)="100"));"



i don't know why??
 

Attachments

  • 1.png
    1.png
    12.9 KB · Views: 200

sandanet

Registered User.
Local time
Yesterday, 18:17
Joined
Oct 14, 2017
Messages
40
Mr. Uncle Gizmo thank you so much ,, i already tried using this tool but i got an error when i put the syntax in vb
 

sandanet

Registered User.
Local time
Yesterday, 18:17
Joined
Oct 14, 2017
Messages
40
sorry guyz, but i couldn't do it correctly
the attached file is my implementation
 

Attachments

  • example.zip
    16.7 KB · Views: 139

isladogs

MVP / VIP
Local time
Today, 02:17
Joined
Jan 14, 2017
Messages
18,252
You can't use double quotes (") in SQL statements.
You either need to use single quotes (') or double double quotes ("")

So for example, your query should probably be
Code:
sql = "SELECT Format(Int((108120-[Value])/3600),'00') AS Total FROM tbl1 WHERE (((tbl1.Property)='100'));"

I say probably as I haven't tested the section Format .... AS.

I would also recommend my SQL to VBA & back again utility as a way of learning how to do such conversions. Its easy & it works!

To convert query SQL to VBA, do the following:
a) Change your query from design view to SQL view. Copy it to the clipboard
b) Open the utility. Click the SQL tab and paste in the query SQL
c) Click the VBA tab and the converted VBA code will be shown.
You can then copy this into a VBA procedure
 

sandanet

Registered User.
Local time
Yesterday, 18:17
Joined
Oct 14, 2017
Messages
40
You can't use double quotes (") in SQL statements.
You either need to use single quotes (') or double double quotes ("")

So for example, your query should probably be
Code:
sql = "SELECT Format(Int((108120-[Value])/3600),'00') AS Total FROM tbl1 WHERE (((tbl1.Property)='100'));"

I say probably as I haven't tested the section Format .... AS.

I would also recommend my SQL to VBA & back again utility as a way of learning how to do such conversions. Its easy & it works!

To convert query SQL to VBA, do the following:
a) Change your query from design view to SQL view. Copy it to the clipboard
b) Open the utility. Click the SQL tab and paste in the query SQL
c) Click the VBA tab and the converted VBA code will be shown.
You can then copy this into a VBA procedure

i did that and i got this
Code:
DoCmd.RunSQL " SELECT Format(Int((108120-[Value])/3600),""00"") AS Total "  & _
" FROM tbl1 "  & _
" WHERE (((tbl1.Property)=""100""));"
now how can i show the result on the form in the unbound textbox ?
 

isladogs

MVP / VIP
Local time
Today, 02:17
Joined
Jan 14, 2017
Messages
18,252
i did that and i got this
Code:
DoCmd.RunSQL " SELECT Format(Int((108120-[Value])/3600),""00"") AS Total "  & _
" FROM tbl1 "  & _
" WHERE (((tbl1.Property)=""100""));"
now how can i show the result on the form in the unbound textbox ?

What you asked for was VBA code to enter into a procedure.
That's what you've got above

If you want to enter the result of a query into a form textbox, you wouldn't do that.
Instead do one of the following:


a) create a form with your query q1 as the record source.
Then add a BOUND textbox with control source = Total field from query
OR
b) create a textbox on your form and set the control source to:
Code:
=DLookUp("Total","q1")
OR
c) create an UNBOUND textbox - I'll call it Text0
Then add code to your form_load event

Code:
Private Sub Form_Load()

    Me.Text0.Value = DLookup("Total", "q1")
        
End Sub

OR
d) create a label (Label0) and set its caption in the Form_Load event
Code:
Private Sub Form_Load()

    Me.Label0.Caption = DLookup("Total", "q1")
        
End Sub

I've done all 4 on a form so you can compare & decide which you want to use.
All work but there is a noticeable delay using method b)
 

Attachments

  • example_CR.accdb
    392 KB · Views: 214

Ranman256

Well-known member
Local time
Yesterday, 21:17
Joined
Apr 9, 2015
Messages
4,337
you cannot use dbl-quotes inside dbl-quotes:
sql = "SELECT Format(Int((108120-[Value])/3600),'00') AS Total FROM tbl1 WHERE (((tbl1.Property)='100'));"
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 02:17
Joined
Jul 9, 2003
Messages
16,293
you cannot use dbl-quotes inside dbl-quotes:
sql = "SELECT Format(Int((108120-[Value])/3600),'00') AS Total FROM tbl1 WHERE (((tbl1.Property)='100'));"

I was thinking the same Ranman and I had to read Collins thread twice to realise that he actually put in double double quotes... So you can't use them individually but you can use them doubled up...

Also Philip shows exactly the same in his excellent YouTube video here:-

Have a look at this excellent video from Phillip should sort out most of your formatting problems there...

VBA SQL Strings - Tutorial for Beginner
 

isladogs

MVP / VIP
Local time
Today, 02:17
Joined
Jan 14, 2017
Messages
18,252
Hi Ranman / Tony

If you look back to post #8, I also used single quotes:
Code:
sql = "SELECT Format(Int((108120-[Value])/3600),'00') AS Total FROM tbl1 WHERE (((tbl1.Property)='100'));"

However, when I created my utility based on a similar idea by Allen Browne, I decided to retain his convention of using double double quotes (rather than convert to single quotes) as it solved various issues during conversion.
Harder to read but it always works.

It can get even more complex...
a) triple double quotes (""") at the end of a text string
Code:
=DLookup("City", "Customers", "CompanyName = ""MendipDataSystems""")
b) use quadruple double quotes ("""") where you need it to be read as ""
Code:
=DLookup("City", "Customers", "CompanyName = """ & [CompanyName] & """")

Yes you could use Chr(34) but in my view that's even harder to read...

Have a look at this article on Allen's site: Quotation marks within quotes

I'm also increasingly using Phillip's site as an excellent reference.
See: http://codekabinett.com/index.php?Lang=2

Unlike Allen he is still very much actively working in Access.
He is also a member of this site with the user name sonic8
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 02:17
Joined
Jul 9, 2003
Messages
16,293
An approach I use where possible is to avoid the issue of building complicated SQL statements. In other words SQL statements with quotes and delimiters in them. Statements built like that are very hard to read and understand particularly for the uninitiated...

My approach is to pass variables into the SQL statement, variables - which have had the delimiters and quote marks added. You end up with a simple SQL Statement which is easy to read, without any clutter of delimiters and quote marks...


Example:-

Code:
Public Function fINSERT_AgeData(ByVal lngRptID As Long, ByVal lngChkID As Long, ByVal lngGrpID As Long, ByVal lngSetsID As Long, ByVal strAgeRangeDesc As String, ByVal lngAgeRangeCount As Long, ByVal strAgeRangeDate As String)

Dim strSQL0 As String
Dim strInsert As String
Dim strValues As String

'Example
'How to Format Text Data
strAgeRangeDesc = Chr(34) & strAgeRangeDesc & Chr(34)
'How to Format Date Data 1
strAgeRangeDate = Chr(35) & strAgeRangeDate & Chr(35)


strInsert = "INSERT INTO tblReporting (ReportID, CheckListID, GrpID, SetsID, ItemsText, ItemsCount, ReportDate) "
strValues = "VALUES (" & lngRptID & ", " & lngChkID & ", " & lngGrpID & ", " & lngSetsID & ", " & strAgeRangeDesc & ", " & lngAgeRangeCount & ", " & strAgeRangeDate & ");"

            strSQL0 = strInsert & strValues
            CurrentDb.Execute strSQL0
 

isladogs

MVP / VIP
Local time
Today, 02:17
Joined
Jan 14, 2017
Messages
18,252
Hi Tony

I often do the same as you - building up lengthy SQL in sections. For example

Code:
strSQL = strSELECT & strWHERE & strORDERBY & ";"

As well as being easier to read/edit, it also has the advantage of solving the
'too many line breaks' issue
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 02:17
Joined
Jul 9, 2003
Messages
16,293
As well as being easier to read/edit, it also has the advantage of solving the
'too many line breaks' issue

Agreed!

Yes Colin, it all boils down to the basic rule of programming, that is, to build your program out of simple, small, easily debugged and managed components.

To my mind using line continuation "& _" violates that principle and I avoid it where possible.

I assign each line of my SQL statement to a string variable.

I have a template file in which I fill in the SQL statements:-

Code:
Dim strSQL0 As String
Dim strSQL1 As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim strSQL4 As String
Dim strSQL5 As String
Dim strSQL6 As String
Dim strSQL7 As String
Dim strSQL8 As String
Dim strSQL9 As String

strSQL1 = ""
strSQL2 = ""
strSQL3 = ""
strSQL4 = ""
strSQL5 = ""
strSQL6 = ""
strSQL7 = ""
strSQL8 = ""
strSQL9 = ""

strSQL0 = strSQL1 & strSQL2 & strSQL3 & strSQL4 & strSQL5 & strSQL6 & strSQL7 & strSQL8 & strSQL9

fSiteBy_PO = strSQL0

The advantage of this approach is as you get in to more advanced programming where you are manipulating SQL Statements, then you can easily build If Statements Case statements etc out of these basic component strings. You just couldn't do that if the string was divided up with the line continuation marks.
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 02:17
Joined
Jul 9, 2003
Messages
16,293
Last edited:

isladogs

MVP / VIP
Local time
Today, 02:17
Joined
Jan 14, 2017
Messages
18,252
Talking of templates, as you may know I've been creating automated function for transforming JSON files into Access tables.

To do this I use a text file as a template, read that into Access then modify individual sections using a special script which is generated automatically for each file

Hard to explain but perhaps slightly simpler with an example

This is a section of a script file

Code:
strSCase = String(12, " ") & "Dim strBase As String, dteDate As Date" & vbCrLf & vbCrLf & _
            String(12, " ") & "|get common values" & vbCrLf & _
            String(12, " ") & "strBase = result('base')" & vbCrLf & _
            String(12, " ") & "dteDate = result('date')" & vbCrLf & vbCrLf & _
            String(12, " ") & "|get string in array" & vbCrLf & _
            String(12, " ") & "lngStart = InStr(1, strJSON, '''rates''') + 9" & vbCrLf & _
            String(12, " ") & "lngEnd = InStr(lngStart, strJSON, '}')" & vbCrLf & _
            String(12, " ") & "strTemp = Mid(strJSON, lngStart, lngEnd - lngStart)" & vbCrLf & _
            String(12, " ") & "|parse string in array" & vbCrLf & _
            String(12, " ") & "arrFieldsValues = Split(strTemp, ',')" & vbCrLf & vbCrLf & _
            String(12, " ") & "For Each varitem In arrFieldsValues" & vbCrLf & _
            String(16, " ") & "varitem = Replace(varitem, '''', '')" & vbCrLf & _
            String(16, " ") & "arrTemp = Split(varitem, ':')" & vbCrLf & vbCrLf & _
            String(16, " ") & ".AddNew" & vbCrLf & _
            String(16, " ") & "!Currency = arrTemp(0)" & vbCrLf & _
            String(16, " ") & "!Rate = arrTemp(1)" & vbCrLf & _
            String(16, " ") & "!Base = strBase" & vbCrLf & _
            String(16, " ") & "!Date = dteDate" & vbCrLf & _
            String(16, " ") & ".Update" & vbCrLf & _
            String(12, " ") & "Next"

As you can see, I'm happy to use "& vbCrLf & _"

When run, this becomes the section between the 2 lines '------------

Code:
'code for table 1 - tblCurrencyExchange
    Set rst = db.OpenRecordset("tblCurrencyExchange", dbOpenDynaset, dbSeeChanges)
    With rst
        For Each result In JSON("result")
            '-------------------------------------
            Dim strBase As String, dteDate As Date

            'get common values
            strBase = result("base")
            dteDate = result("date")

            'get string in array
            lngStart = InStr(1, strJSON, """rates""") + 9
            lngEnd = InStr(lngStart, strJSON, "}")
            strTemp = Mid(strJSON, lngStart, lngEnd - lngStart)
            'parse string in array
            arrFieldsValues = Split(strTemp, ",")

            For Each varitem In arrFieldsValues
                varitem = Replace(varitem, """", "")
                arrTemp = Split(varitem, ":")

                .AddNew
                !Currency = arrTemp(0)
                !Rate = arrTemp(1)
                !Base = strBase
                !Date = dteDate
                .Update
            Next
            '-------------------------------------

        Next
        .Close
    End With

Horrendously complex to get it correct but it now works beautifully....
 

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 02:17
Joined
Jul 9, 2003
Messages
16,293
What does the "String(12, " ")" and 16 do?
 

Users who are viewing this thread

Top Bottom