SQL statement in VBA

Hi,

I want to use this SQL code in VBA.

SELECT Currencies.*, Countries.*
FROM Countries RIGHT JOIN Currencies ON Countries.[Country ID] = Currencies.
[Country ID];

Help appreciated on correct syntax.

Thanks.

-- 
Message posted via AccessMonster.com
http://www.accessmonster.com/Uwe/Forums.aspx/access-modules/201002/1

0
killeronloose
2/16/2010 9:41:00 AM
access.modulesdaovba 1670 articles. 0 followers. Follow

7 Replies
987 Views

Similar Articles

[PageSpeed] 23

hi,

On 16.02.2010 10:41, killeronloose via AccessMonster.com wrote:
> I want to use this SQL code in VBA.
What do you like to do with it?

imho the most common scenario:

Public Sub Foo()

   Dim rs As DAO.Recordset

   Dim sql As String

   sql = "SELECT Cu.*, Co.* " & _
         "FROM Countries Co " & _
         "RIGHT JOIN Currencies Cu " & _
         "ON Co.[Country ID] = Cu.[Country ID];"

   Set rs = CurrentDb.OpenRecordset(sql, dbOpenSnapshot)
   ' Do something with rs, e.g.:
   MsgBox "Found " & rs.RecordCount & " records."
   rs.Close
   Set rs = Nothing

End Sub

mfG
--> stefan <--
0
Stefan
2/16/2010 9:53:26 AM
I have this query in an accdb file. I am looking to create this query through
VBA (CreateQueryDef), but can't seem to get correct syntax.

Stefan Hoffmann wrote:
>hi,
>
>> I want to use this SQL code in VBA.
>What do you like to do with it?
>
>imho the most common scenario:
>
>Public Sub Foo()
>
>   Dim rs As DAO.Recordset
>
>   Dim sql As String
>
>   sql = "SELECT Cu.*, Co.* " & _
>         "FROM Countries Co " & _
>         "RIGHT JOIN Currencies Cu " & _
>         "ON Co.[Country ID] = Cu.[Country ID];"
>
>   Set rs = CurrentDb.OpenRecordset(sql, dbOpenSnapshot)
>   ' Do something with rs, e.g.:
>   MsgBox "Found " & rs.RecordCount & " records."
>   rs.Close
>   Set rs = Nothing
>
>End Sub
>
>mfG
>--> stefan <--

-- 
Message posted via http://www.accessmonster.com

0
killeronloose
2/16/2010 10:19:31 AM
hi,

On 16.02.2010 11:19, killeronloose via AccessMonster.com wrote:
> I have this query in an accdb file. I am looking to create this query through
> VBA (CreateQueryDef), but can't seem to get correct syntax.
hmm, providing a concise and complete example would have been nice...

Option Compare Database
Option Explicit

Public Sub CreateQuery(AQueryName As String)

   On Local Error Resume Next

   Dim db As DAO.Database
   Dim qd As DAO.QueryDef

   Dim errorNumber As Long
   Dim sql As String

   Set db = CurrentDb
   Set qd = db.QueryDefs.Item(AQueryName)
   errorNumber = Err.Number

   On Local Error GoTo LocalError

   sql = "SELECT * " & _
         "FROM Countries AS Co " & _
         "RIGHT JOIN Currencies AS Cu " & _
         "ON Co.[Country ID] = Cu.[Country ID];"

   If errorNumber = 3265 Then
     ' Query does not exist, create it.
     db.CreateQueryDef AQueryName, sql
   Else
     ' Otherwise modify the existing one.
     qd.sql = sql
   End If
   db.QueryDefs.Refresh

   Set qd = Nothing
   Set db = Nothing

   Exit Sub

LocalError:
   MsgBox Err.Description, vbCritical

End Sub

btw, you should avoid

a) using special characters in field and/orobject names.
b) naming tables using pluralization.

mfG
--> stefan <--

0
Stefan
2/16/2010 11:32:53 AM
You don't need to have a saved query in order to execute it, you can very 
well execute an ad hoc query, but here is another (simpler?) way to create a 
query:

CurrentProject.Connection.Execute "CREATE PROC queryNameYouWant AS SELECT 
Currencies.*, Countries.* FROM Countries RIGHT JOIN Currencies ON 
Countries.Country ID] = Currencies.[Country ID]; "


(note that is it only one line.)


It requires Jet 4.0  (since we CREATE a stored PROCedure without parameter)


Vanderghast, Access MVP

0
vanderghast
2/16/2010 1:44:15 PM
I have two tables - Currencies and Countries.

Countries have two fields - [Country ID] and Name
Currencies have three fields - ID, Name and [Country ID].

I have to make a form to insert data in Currencies table. Since the user will
have to choose [Country ID] by data sourced from Countries table, I decided
to make a query by joining the tables and then make the form based on this
query.

SELECT Currencies.*, Countries.*
FROM Countries RIGHT JOIN Currencies ON Countries.[Country ID] = Currencies.
[Country ID];

While I am able to make query through query design, I am unable to do so from
VBA. The error "3131: Syntax error in FROM clause" appears no matter what I
try.


Stefan Hoffmann wrote:
>hi,
>
>> I have this query in an accdb file. I am looking to create this query through
>> VBA (CreateQueryDef), but can't seem to get correct syntax.
>hmm, providing a concise and complete example would have been nice...
>
>Option Compare Database
>Option Explicit
>
>Public Sub CreateQuery(AQueryName As String)
>
>   On Local Error Resume Next
>
>   Dim db As DAO.Database
>   Dim qd As DAO.QueryDef
>
>   Dim errorNumber As Long
>   Dim sql As String
>
>   Set db = CurrentDb
>   Set qd = db.QueryDefs.Item(AQueryName)
>   errorNumber = Err.Number
>
>   On Local Error GoTo LocalError
>
>   sql = "SELECT * " & _
>         "FROM Countries AS Co " & _
>         "RIGHT JOIN Currencies AS Cu " & _
>         "ON Co.[Country ID] = Cu.[Country ID];"
>
>   If errorNumber = 3265 Then
>     ' Query does not exist, create it.
>     db.CreateQueryDef AQueryName, sql
>   Else
>     ' Otherwise modify the existing one.
>     qd.sql = sql
>   End If
>   db.QueryDefs.Refresh
>
>   Set qd = Nothing
>   Set db = Nothing
>
>   Exit Sub
>
>LocalError:
>   MsgBox Err.Description, vbCritical
>
>End Sub
>
>btw, you should avoid
>
>a) using special characters in field and/orobject names.
>b) naming tables using pluralization.
>
>mfG
>--> stefan <--

-- 
Message posted via AccessMonster.com
http://www.accessmonster.com/Uwe/Forums.aspx/access-modules/201002/1

0
killeronloose
2/17/2010 6:44:01 AM
"killeronloose via AccessMonster.com" <u58153@uwe> wrote in message 
news:a3c16cd78d1b3@uwe...
>I have two tables - Currencies and Countries.
>
> Countries have two fields - [Country ID] and Name
> Currencies have three fields - ID, Name and [Country ID].
>
> I have to make a form to insert data in Currencies table. Since the user 
> will
> have to choose [Country ID] by data sourced from Countries table, I 
> decided
> to make a query by joining the tables and then make the form based on this
> query.
>
> SELECT Currencies.*, Countries.*
> FROM Countries RIGHT JOIN Currencies ON Countries.[Country ID] = 
> Currencies.
> [Country ID];
>
> While I am able to make query through query design, I am unable to do so 
> from
> VBA. The error "3131: Syntax error in FROM clause" appears no matter what 
> I
> try.
>
>
> Stefan Hoffmann wrote:
>>hi,
>>
>>> I have this query in an accdb file. I am looking to create this query 
>>> through
>>> VBA (CreateQueryDef), but can't seem to get correct syntax.
>>hmm, providing a concise and complete example would have been nice...
>>
>>Option Compare Database
>>Option Explicit
>>
>>Public Sub CreateQuery(AQueryName As String)
>>
>>   On Local Error Resume Next
>>
>>   Dim db As DAO.Database
>>   Dim qd As DAO.QueryDef
>>
>>   Dim errorNumber As Long
>>   Dim sql As String
>>
>>   Set db = CurrentDb
>>   Set qd = db.QueryDefs.Item(AQueryName)
>>   errorNumber = Err.Number
>>
>>   On Local Error GoTo LocalError
>>
>>   sql = "SELECT * " & _
>>         "FROM Countries AS Co " & _
>>         "RIGHT JOIN Currencies AS Cu " & _
>>         "ON Co.[Country ID] = Cu.[Country ID];"
>>
>>   If errorNumber = 3265 Then
>>     ' Query does not exist, create it.
>>     db.CreateQueryDef AQueryName, sql
>>   Else
>>     ' Otherwise modify the existing one.
>>     qd.sql = sql
>>   End If
>>   db.QueryDefs.Refresh
>>
>>   Set qd = Nothing
>>   Set db = Nothing
>>
>>   Exit Sub
>>
>>LocalError:
>>   MsgBox Err.Description, vbCritical
>>
>>End Sub
>>
>>btw, you should avoid
>>
>>a) using special characters in field and/orobject names.
>>b) naming tables using pluralization.
>>
>>mfG
>>--> stefan <--
>
> -- 
> Message posted via AccessMonster.com
> http://www.accessmonster.com/Uwe/Forums.aspx/access-modules/201002/1
>

Dim s As String

s = "SELECT Currencies.*,"
s = s & "Countries.*"
s = s & " FROM Countries"
s = s & " RIGHT JOIN Currencies"
s = s & " ON Countries.[Country ID] = Currencies."
s = s & " [Country ID];"


0
Stuart
2/17/2010 7:23:30 AM
Done. Thanks to everyone.

Stuart McCall wrote:
>>I have two tables - Currencies and Countries.
>>
>[quoted text clipped - 76 lines]
>>>mfG
>>>--> stefan <--
>
>Dim s As String
>
>s = "SELECT Currencies.*,"
>s = s & "Countries.*"
>s = s & " FROM Countries"
>s = s & " RIGHT JOIN Currencies"
>s = s & " ON Countries.[Country ID] = Currencies."
>s = s & " [Country ID];"

-- 
Message posted via AccessMonster.com
http://www.accessmonster.com/Uwe/Forums.aspx/access-modules/201002/1

0
killeronloose
2/17/2010 8:49:22 AM
Reply:

Similar Artilces:

Calling Dex Procedures from SQL
Is there any way to call dex procs from SQL or VB code? Jed There is an undocumented and unsupported method of calling Dex code from VBA. However, I know of no method of calling Dexterity from SQL. Please email me if you want an example, just remove the online. from the address below. David Musgrave [MSFT] Senior Development Consultant MBS Services - Asia Pacific Microsoft Business Solutions http://www.microsoft.com/BusinessSolutions mailto:dmusgrav@online.microsoft.com Any views contained within are my personal views and not necessarily Microsoft Business Solutions policy. This p...

how to create an excel vba phone book?
I have several contacts (mobile number and email id) in excel sheet. How can i create a contact book with search function by using vba in excel? On Oct 16, 4:07=A0am, Achu Prasad <achupras...@gmail.com> wrote: > I have several contacts (mobile number and email id) in excel sheet. How = can i create a contact book with search function by using vba in excel? more explanation? for example I have one excel sheet with name of employee, mobile number, email id and employee code how can i create an excel vba programme by uploading the sheet i hav and i want a search function in it to sear...

need site to learn VBA for excel-beginers
Hi everyone Can anyone provide some links to learn VBA for excel - for beginners?? Thanks GT --- Message posted from http://www.ExcelForum.com/ Here's Norman Harker's standard response to this Try the following: http://support.microsoft.com/default.aspx?scid=/support/excel/content/vba101/default.asp But a good list of websites is also useful: Chip Pearson: http://www.cpearson.com/excel/topic.htm Dave McRitchie http://www.mvps.org/dmcritchie/excel/xlindex.htm John Walkenbach http://j-walk.com/ss/excel/index.htm Ron de Bruin www.rondebruin.nl/Google.htm Ron has an Add-In tha...

AutoSave File After X Time In VBA
Can Someone Please Help. I want to create a macor somewhere in my spreadsheet to automatical save the file after a predetermined time, then the timer would the start again, or at least once any changes are made. Can this be done? Thanks Celtic_Avenger :confused: :confused: :confused: :confused: :confused -- Celtic_Avenge ----------------------------------------------------------------------- Celtic_Avenger's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1410 View this thread: http://www.excelforum.com/showthread.php?threadid=26126 Before xl2k, this was...

is SQL 2000 architecture different SQL Server 2005 / 2008 architecture?
Hi I have a book "inside SQL Server 2000" by Kalen Delaney, which I have been told is a good book. I am going backwards... reading about the sql server architecture in chapter 3 of the book. As I'm reading... I was wondering is it different SQL Server 2000 vs SQL Server 2005/2008? Also where can I find a book/or link that can give me more details about the internals on architecture? Thank you norm (normanchan@gmail.com) writes: > Hi I have a book "inside SQL Server 2000" by Kalen Delaney, which I > have been told is a good book. I am g...

VBA Issue
I have created a report takes a report form template and creates an .snp file for each timekeeper. I get my timekeeper list using the following snippet of code Dim strSQL, conn1, lstRptName As String Dim db As Database Dim rst, oRS As Recordset Set db = CurrentDb strSubject = "Stripped Down Countdown" Set rst = db.OpenRecordset("select distinct head1 as mbillaty from dbo_prj_cash_base, dbo_matter, timekeep, dbo_client where clnum=mclient and mbillaty=tkinit and mmatter=matter and mprac< 1000 group by head1 having sum(togo_fees)> 49") This worked fine last ...

Moving customizations from SQL 2k to SQL 2k5 CRM
This may be a non-issue but I wanted to check to see if anyone has done this and ran into issues. I have the XML customization files from our previous install of CRM 3.0 with SQL 2k database. I now want to import and publish these same customizations to CRM 3.0 on SQL 2k5. Has anyone done this or can point me to documentation that tells about the success or issues for doing this? Thanks. On 7 Feb., 06:35, Chris Treanor <ChrisTrea...@discussions.microsoft.com> wrote: > This may be a non-issue but I wanted to check to see if anyone has done this > and ran into issues. > &...

VBA Question #4
Hi: I have BASIC programming skills but have never had the opportunity to use VBA inside Excel. Using a UDF, I need to know how to take the contents of a cell and pass it to a variable inside my user defined function. I am trying to take the results in one cell and if it matches, then take the information from two other cells and multiply them together. I've poured over the VBA documentation and see how to push a value into a cell, but can't find any examples of retrieving a cell's content. Thanks in advance! -- Steve Spence Independent AMSOIL Dealer AMSOIL - The "...

CRM 3.0 Install Error with SQL Reporting Services and SQL 2005
Hi, Doing a CRM 3.0 Server installation. During the last page of the install wizard (or what I assume is the last page) when I goes through and does verification I get a red X next to SQL Reporting Services. The message I receive when I look at the details is: ***** The specified path is not a metabase path. Parameter name: path ***** Now SRS is installed and working. I put in the URL: http://<servername>/reportserver and every other variation on that I can find. Thoughts? Alan try http://servername/reports also assuming you did not use ssl... =======================...

Need to add check transactions to Microsoft Money using OFX file (not bank statements)
Does anybody have an example of an OFX file that imports check transactions into Microsoft Money? I need to simulate the manual input of checks. Dut to problems in our accounting software, it's best to enter transactions in our accounting system and rekey them into MS-Money. I found some "statement" files but I am thinking this isn't what I need to do????? I appreciate the depth and functionality of ofx vs. qif but I am finding it difficult to find ofx examples since they all appear to be produced by large companies (i.e. banks and financial companies) Any help wo...

MS Office VBA Automation Specialist
Hi there, is there such a certificate? MS Office VBA Automation Specialist, I tried 'googling ' (http://tinyurl.com/bo9oe) it on microsoft website and couldn't find any info. I just passed the excel 2k expert exam and I want to take the excel instructor exam, I haven't however been an instructor. is it possible to take the exam without an instructor experience? last but not least, I am thinking about putting together some excel webcasts for beginners for free. I have always liked to learn by audio/visual versus reading so I am thinking about implementing this with the little ...

SQL 'for xml' and C# example??
I'm missing some piece of the puzzle. I'm using 'for xml' type queries from SQL2K - and now trying to change the front-end from ADO to C#, I can't quite figure it out.. It seems that I could use an XmlReader.. and somehow use that instead of a DataReader.. but that didn't work.. I tried using a DataReader and get the byte array - but that wasn't right. SQL returns formatted XML, I need to load that XML into an XmlDocument somehow without ANY molestation of that dom. Any ideas? Examples? Missing links???? thanks THANKS!! I've been looking for the answer to ...

sql summarizing help
Hi All, Given: table1 --------- id, cdate, weeksago, amount, typeid, timeclose 496, 2010-02-11, 0, 450, 3, 1 490, 2010-02-01, 1, 200, 4, 1 491, 2010-02-01, 1, 350, 2, 2 493, 2010-02-01, 1, 500, 5, 1 489, 2010-01-21, 3, 150, 2, 1 136, 2010-01-12, 4, 500, 3, 2 137, 2010-01-12, 4, 100, 3, 1 138, 2010-01-12, 4, 500, 2, 1 1. i'm trying to create a sql that will give me a summary resultset grouped by weeksago. 2. i want to sum the columns and get counts based on typeid. 3. avg of timeclose here's the sql i have: select weeksago, , (sum(timeClose)/(count(timeclo...

Update multivalue field in table from form with SQL
Access 2007 on Vista I am using a form to establish the variables for a report before it is created. One field on the underlying table is a multivalue field, and the form includes a multi-select combo box control. After selections are made and the OK button on the multi-select combo drop down is clicked, focus moves to the next control. I have discovered though, that the underlying table does not update immediately, but does so correctly when I close the form. This sequence does not deliver the proper report data, so I need a way to immediately update the underlying table (m...

using Forms and VBA within Excel
I need to develop an application with Excel which will include Forms and VBA code. I have done small projects like this before but this will be significantly larger with 6-10 forms and navigation (via command buttons) between the forms. I have heard rumors that forms within Excel can be troublesome (e.g. they can disappear without warning). I have never had problems with this before. But still wanted to ask the community - are there know issues with using Forms and VBA within Excel. The main functionality of the app will be to validate and capture data, store the data in Excel a...

Excel VBA help
I am needing some help with this vba code. What I am trying to do is first verify if cell A4 is not empty, if it is not empty then I need it to make sure there is data in the other columns before anyone can save. This is what I got so far but it is saving and not bring the popup message that data is missing. Private Sub Workbook_BeforeSave(ByVal SaveAsUi As Boolean, Cancel As Boolean) If IsEmpty(A4) = False Then 'make sure that A4 is not empty prior to running the below if If Worksheets("User's Sheet").Range("B4").Value = "" Then ...

If Statements- New User
Good Afternoon, Could someone please be of assistance. I am currently a new user and I am having difficulty with "IF" statements. I am working on a spread sheet that has various departments: Art, Design, Liberal Studies, ect. I want to creat a statement that has the following: If 1000 then it should read faculty of Art If 1300 then it should read faculty of Design If 1700 then it should read liberal studies etc. I keep trying to do this but if keeps giving me error messages. I'm hoping someone can help. If statements can't be that complicated. Are they? Many Thanks Mo...

Refer to SQL statements globally
I have two large SQL statements that I need to use across several forms, reports, etc. Rather than repeat them in each form, I'm trying to store and reference them globally. For example, I'd like to store strSQL1 and strSQL2 in a global module, so I can use either like this in a form: Random form: Me!lstResults.RowSource = strSQL1 Random report: Me.Report.RecordSource = strSQL2 Would I just store the SQL statements in a global module like: Public Function SQLSource() As String Dim strSQL1 As String Dim strSQL2 As String strSQL1 = "SELECT blah blah...

To SQL or not to SQL?
I have a very vertical product developed 100% in M/S Access. I developed it myself in 1993 in the initial release of Access and been with it ever since. It is currently very stable and running in Access 2003. My big question is how or even *if* we should move it to SQL. My customers are getting bigger all the time with more users. Typically our customers run one or two workstations generally never more than 5. Performance, however, is starting to slow with database sizes passing 500 meg. We also have a LOT of code behind forms so are bound tightly to the Access development environ...

PostgreSQL or other SQL servers in RMS
Has anyone successfully implemented RMS with one of the free SQL servers? Theoretically, is there any reason why we have to use MS SQL Server 2000 for large databases? David "dh" <dh@discussions.microsoft.com> ha scritto nel messaggio news:1783A90D-AF3E-4D91-A445-0039D4E7E379@microsoft.com... > Has anyone successfully implemented RMS with one of the free SQL servers? > Theoretically, is there any reason why we have to use MS SQL Server 2000 > for > large databases? RMS has implemented only for MS SQL Server (2000/MSDE) and isn't possible to work with ano...

Excel vba autofilter code
I have some code to filter a result set to a list of unique names - is there something I can add that will also remove 'blank' entries ? Range("AP1:AP" & LastRowNewData).AdvancedFilter _ Action:=xlFilterCopy, _ CopyToRange:=Range("A44"), _ Unique:=True Thanks ...

writeback to SQL 2005
hello! I use excel 2007 iI open a connection agianst SQL server 2005 and choose a table. In my workbook i can now see this data from this table. if i change a value in some cell i wish to writeback to table in SQL server. Is this possible? It's possible through the use of VBA and ADO, but not simply using the data connection you've already established. Ross "CJ" <CJ@discussions.microsoft.com> wrote in message news:D54EC521-0DD5-4B3D-971B-4FF3394D6FA8@microsoft.com... > hello! I use excel 2007 > iI open a connection agianst SQL server 2005 and choose a table...

Error handling in VBA
Hi guys, I'm not so used to the On Error statement, ssince I come from a Fortran background where all error handling must be performed using If Then Else constructs. Example: in this interpolation subroutine 'Returns an interpolated value of x 'doing a lookup of xarr->yarr Public Function Interp1(xArr() As Double, yArr() As Double, X As Double) As Double Dim I As Long If ((X < xArr(LBound(xArr))) Or (X > xArr(UBound(xArr)))) Then MsgBox "Interp1: x is out of bound" Stop Exit Function End If If xArr(LBound(xArr)) = X Then Interp1 ...

sql.request #2
Does anyone have a comprehensible guide on how to use it that a dolt like me can follow? Every time I try I get a #N/A. The only guide I can find is at http://www.bygsoftware.com/examples/zipfiles/UsingSqlRequest.zip but it's really hard to follow. From the MSDN Library: http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/office97/html/SEC41.asp Not sure how familiar you are with ODBC; but if you are getting #N/A as a result, it is usually because of problems either with the SQL syntax or the connection string. There are a few examples of connection strings in the re...

MSDE or SQL Personal or SQL Developer? or SQL Workstation?
Hi, which one is better for personal non-server computer? MSDE? SQL Personal? SQL Developer? SQL Workstation? Thank you. It depends on what edition of GP you are going to run. If you are going to use Professional, you need to go with SQL Server developer, assuming you are installing on a non-server OS. "ano" wrote: > Hi, which one is better for personal non-server computer? MSDE? SQL Personal? > SQL Developer? SQL Workstation? > Thank you. Is the function of SQL Developer the same as Enterprise edition? How about personal edition? Can it be used for GP Pro? Can dev...