Provided by Allen Browne. Created: March 2007. Last Updated: November 2008.
Copy SQL statement from query to VBA
Rather than typing complex query statements into VBA code, developers often mock up a query graphically, switch it to SQL View, copy, and paste into VBA.
If you've done it, you know how messy it is sorting out the quotes, and the line endings.
Solution: create a form where you paste the SQL statement, and get Access to create the SQL string for you.
Creating the form
The form just needs two text boxes, and a command button. SQL statements can be quite long, so you put the text boxes on different pages of a tab control.
- Create a new form (in design view.)
- Add a tab control.
- In the first page of the tab control, add a unbound text box.
Set its Name property to txtSql.
Increase its Height and Width so you can see many long lines at once.
- In the second page of the tab control, add another unbound text box.
Name it txtVBA, and increase its height and width.
- Above the tab control, add a command button.
Name it cmdSql2Vba.
Set its On Click property to [Event Procedure].
Click the Build button (...) beside this property.
When Access opens the code window, set up the code like this:
Private Sub cmdSql2Vba_Click()
Dim strSql As String
Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """"
If IsNull(Me.txtSQL) Then
Beep
Else
strSql = Me.txtSQL
strSql = Replace(strSql, """", """""")
strSql = Replace(strSql, vbCrLf, strcLineEnd)
strSql = "strSql = """ & strSql & """"
Me.txtVBA = strSql
Me.txtVBA.SetFocus
RunCommand acCmdCopy
End If
End Sub
Using the form
To use the form:
- Open your query in SQL View, and copy the SQL statement to clipboard (Ctrl+C.)
- Paste into the first text box (Ctrl+V.)
- Click the button.
- Paste into a new line in your VBA procedure (Ctrl+V.)
Hint: If you want extra line breaks in your VBA code, press Enter to create those line breaks in the SQL View of the query or in your form.
Access 97 and earlier
These versions lacked the Replace() function. To use the code with those versions, copy the custom Replace() function from this utility.