user11349745
user11349745

Reputation:

VBA if statement before executing SQL?

How can I correctly write an if statement in MS Access VBA that checks if the value in a textbox located on a form is equal to a record in a table column?

The form is called FormExample has a textbox called TextBoxExample. The table is called Table1 and the record being updated is TestTrial where the NumberValue column matches what is in TextBoxExample.

If it is equal than execute the following SQL query:

UPDATE Table1 SET Table1.TestTrial = "Test11"
WHERE (((Table1.NumberValue)=[Forms]![FormExample]![TextBoxExample]));

If not display the following message:

MsgBox "Sorry" & _
            vbCrLf

Upvotes: 1

Views: 55

Answers (1)

Strawberryshrub
Strawberryshrub

Reputation: 3399

To check if the value in the textbox is the same like in the table use a DCount() (DLookup() would also be possible). I assume, that your textbox value is a Double because your value is called NumberValue.

Dim textboxValue As Double
Dim lookupValue As Double

textboxValue = Me!TextBoxExample.Value
lookupValue = DCount("TestTrial", "Table1", "NumberValue = " & textboxValue)

If Not lookupValue = 0 Then
  Msgbox "One or more records where found."
Else
  Msgbox "No record was found."
End If

Upvotes: 1

Related Questions