Use bookmark value in WORD for sql query - sql

I am currently trying to build an automated WORD business letter that fills out corresponding data such as company address, company name, today's date, deadline date and so on after I have typed in a 5 digit number.
The number and all other fields are bookmarks.
Whenever the user types in a specific 5 digit number into the bookmark named "theNumber", this value will be used for an SQL query (Oracle). The query then fills out all other bookmarks!
Here is what I have tried so far:
Function dbQuery(ByVal TM As String, ByVal myNumber As String) As Boolean
Dim sqlrumpf As String
Dim sqlstring As String
Dim connstring As String
With ActiveDocument
If .Bookmarks.Exists(TM) Then
Dim TMRange As Range
Set TMRange = .Bookmarks(TM).Range
TMRange = myNumber
.Bookmarks.Add TM, TMRange
dbQuery = True
Else
Debug.Print "Bookmark not found: " & TM
End If
End With
sqlrumpf = "SELECT p.name " & _
"FROM xy.person p, xy.adresse a, wz.zusatz1 z, xy.vorgang v " & _
"WHERE p.adresse_id = a.adresse_id " & _
"AND z.aktnr = v.vorgang_id " & _
"AND a.adresse_id = v.adresse_id " & _
"AND v.vorgang_nr = '"
sqlstring = sqlrumpf & myNumber & "'"
connstring = "ODBC;DSN=mydsn;UID=myuid;DBQ=my.dbq.lan;DBA=W;APA=T;PFC=1;TLO=0;PWD=mypw;"
QueryTables.Add _
(Connection:=connstring, _
Destination:=Range(TMRange), _
Sql:=sqlstring).Refresh
End Function
Sub Main()
If dbQuery("theNumber", "12345") = False Then
MsgBox "Database query failed!"
End If
End Sub
I get the error:
Runtime Error '4608': Value not within definition range.
How can I fix this?
The error seems to occur here:
Destination:=Range(TMRange), _
Normally I use this query only for excel when I want to print a query into a single cell.
Is it generally a bad idea to use bookmarks with sql queries in this manner?
Which fields would you use if not bookmarks?
How do you query bookmark values?

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

Looping through table to find value from a textbox

I'm trying to loop through a column inside a table from a form in Access to find out whether a "Case Name" already exists or not, and if it does not, then add the new record to the table. I want the criteria to be based on the input value of a text box. The good news is I have figured out how to add a new record to the table with the code below. I'm just stuck on how to loop through a table to find out if a record already exists. Thanks in advance!
Private Sub SaveNewCase_Click()
If Me.txtNewCaseName.Value <> "Null" And Me.txtCaseDepth.Value <> "Null" And Me.txtCaseHeight2.Value <> "Null" And Me.txtCaseWeight.Value <> "Null" And Me.txtCaseWidth <> "Null" And Me.cboCaseCategory.Value <> "Null" Then
'I think the loop should go here, but not sure'
CurrentDb.Execute "INSERT INTO tblCases(CaseName, CaseWidth, CaseHeight, CaseCasters, CaseWeight, CaseDepth, CaseCategory) " & _
" VALUES ('" & Me.txtNewCaseName & "'," & Me.txtCaseWidth & "," & Me.txtCaseHeight2 & ",'" & Me.chkboxCasters & "'," & Me.txtCaseWeight & "," & Me.txtCaseDepth & ",'" & Me.cboCaseCategory & "')"
Else
MsgBox "Please enter all new case criteria."
End If
End Sub
Firstly, use parameters!
Concatenating values supplied by a user directly into your SQL statement exposes your to SQL injection, either intentional (i.e. users entering their own SQL statements to sabotage your database) or unintentional (e.g. users entering values containing apostrophes or other SQL delimiters).
Instead, represent each of the field values with a parameter, for example:
With CurrentDb.CreateQueryDef _
( _
"", _
"insert into " & _
"tblcases (casename, casewidth, caseheight, casecasters, caseweight, casedepth, casecategory) " & _
"values (#casename, #casewidth, #caseheight, #casecasters, #caseweight, #casedepth, #casecategory) " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
.Execute
End With
Since the value of each form control is fed directly to the parameter within the SQL statement, the value will always be interpreted as a literal and cannot form part of the SQL statement itself.
Furthermore, you don't have to worry about surrounding your string values with single or double quotes, and you don't have to worry about formatting date values - the data is used in its native form.
Where testing for an existing value is concerned, you can either use a domain aggregate function, such as DLookup, or you could use a SQL select statement and test that no records are returned, e.g.:
Dim flg As Boolean
With CurrentDb.CreateQueryDef _
( _
"", _
"select * from tblcases where " & _
"casename = #casename and " & _
"casewidth = #casewidth and " & _
"caseheight = #caseheight and " & _
"casecasters = #casecasters and " & _
"caseweight = #caseweight and " & _
"casedepth = #casedepth and " & _
"casecategory = #casecategory " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
With .OpenRecordset
flg = .EOF
.Close
End With
End With
If flg Then
' Add new record
Else
' Record already exists
End If
Finally, you're currently testing the values of your form controls against the literal string "Null", which will only be validated if the user has entered the value Null into the control, not if the control is blank.
Instead, you should use the VBA IsNull function to check whether a variable holds a Null value.

MS Access. VBA. How to create a temporary table with 1 record only if it not exist

I am looking for a way to Create a table when Form is opening.
Table should be created just once. So if it exists new one should not be created.
In the same form I would like to save some data from combo boxes in created table.
To do that I tried to use a code:
Sub ViaVBA()
Const strSQLCreateFoo_c As String = _
"CREATE TABLE Foo" & _
"(" & _
"MyField1 INTEGER," & _
"MyField2 Text(10)" & _
");"
Const strSQLAppendBs_c As String = _
"INSERT INTO Foo (MyField1, MyField2) " & _
"SELECT Bar.MyField1, Bar.MyField2 " & _
"FROM Bar " & _
"WHERE Bar.MyField2 Like 'B*';"
If Not TableExists("foo") Then
CurrentDb.Execute strSQLCreateFoo_c
End If
CurrentDb.Execute strSQLAppendBs_c
End Sub
Private Function TableExists(ByVal name As String) As Boolean
On Error Resume Next
TableExists = LenB(CurrentDb.TableDefs(name).name)
End Function
Unfortunately it is not saving selected values from combo boxes.
It seems that the table has no records and it doesn't want to save the values.
When I add at least one record that combo boxes are storing correct values.
How to create a table with one record with some dummy info using the code posted above?
Concatenate variable input. Delimit parameters for text field with apostrophes. Use VALUES clause instead of SELECT. Use If Then instead of WHERE clause to test value of form control. Don't use reserved word Name as variable.
Consider:
Sub ViaVBA()
If Not TableExists("foo") Then
CurrentDb.Execute "CREATE TABLE Foo(MyField1 INTEGER, MyField2 Text(10));"
End If
If Forms!Bar.MyField2 LIKE "B*" Then
CurrentDb.Execute "INSERT INTO Foo (MyField1, MyField2) " & _
"VALUES(" & Forms!Bar.MyField1 & ", '" & Forms!Bar.MyField2 & "')"
End If
End Sub
Private Function TableExists(ByVal strName As String) As Boolean
On Error Resume Next
TableExists = LenB(CurrentDb.TableDefs(strName).Name)
End Function

SQL query works in access but not in excel

I need to get data from a recordset. The SQL query works fine in MS Access and returns exactly the expected values, but when the same query is lunched in VBA Excel, I get the following error:
No value given for one or more required parameters
Do you have any ideas why this problem occurs?
Thank you.
Philippe-Olivier Roussel
Private Sub CBtype_AfterUpdate()
Dim strConnexion As String
Dim connexion As New ADODB.Connection
strConnexion = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Database & ""
connexion.Open strConnexion
Dim rsMarque As New ADODB.Recordset
Dim seltype As String
seltype = CBtype.Value
rsMarque.Open "SELECT DISTINCT tblMarque.marque_nom FROM tblMarque, tblModele WHERE " & _
" tblMarque.marque_id = tblModele.marque_id AND tblModele.marque_id IN " & _
" (SELECT DISTINCT tblModele.marque_id FROM tblModele, tblType " & _
" WHERE tblModele.type_id = tblType.type_id AND tblModele.type_id = " & _
" (SELECT tblType.type_id FROM tblType WHERE " & _
" (tblType.type_nom = " & seltype & ")))", connexion, adOpenStatic
rsMarque.MoveFirst
With UserForm2.CBmarque
.Clear
Do
.AddItem rsMarque!marque_nom
rsMarque.MoveNext
Loop Until rsMarque.EOF
End With
End Sub
This error message looks like an output from the DBMS rather than Excel
I think you might be missing the apostrophe before and after your string variable. See if
" (tblType.type_nom = '" & seltype & "')))" works (I'm assuming the column you're querying is varchar type, since you declared seltype as string)

data type mismatch on criteria expression

I have three tables with the exact same data fields and data types. I am trying to create a search form using one combo box for three subforms. I tried changing the String to Integer but I always end up with the same error: "Data type mismatch on criteria expression". What am I doing wrong here.
Private Sub cboAlarmSearch_AfterUpdate()
Dim SpotAlarm As String
Dim ProgressAlarm As String
Dim FinalAlarm As String
Dim strAlarmCriteria As String
If IsNull(Me.cboAlarmSearch) Or Me.cboAlarmSearch = "" Then
MsgBox "Please choose an Alarm to search.", vbOKOnly, "Alarm Required"
Else
strAlarmCriteria = Me.cboAlarmSearch.Value
'Alarm search for Spot
SpotAlarm = "Select * FROM tblSpot WHERE ([Alarm] = '" & strAlarmCriteria & "')"
Me.frmSpotSearchSubform.Form.RecordSource = SpotAlarm
Me.frmSpotSearchSubform.Form.Requery
'Alarm search for Progress
ProgressAlarm = "Select * from tblProgress WHERE ([Alarm] = '" & strAlarmCriteria & "')"
Me.frmProgressSearchSubform.Form.RecordSource = ProgressAlarm
Me.frmProgressSearchSubform.Form.Requery
'Alarm search for Final
FinalAlarm = "Select * from tblFinal WHERE ([Alarm] = '" & strAlarmCriteria & "')"
Me.frmFinalSearchSubform.Form.RecordSource = FinalAlarm
Me.frmFinalSearchSubform.Form.Requery
End If
End Sub