BaldyWeb
A Tutorial on Building SQL in VBA, part 2
Referencing form controlsPrivate Sub cmdSearch_Click()
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "SELECT * FROM tblEmployee " & _
"WHERE [EmployeeName] = " & Chr$(39) & Me.txtEmployeeName & Chr$(39)
Set rs = CurrentDb.OpenRecordset(strSQL)
Debug.Print strSQL
Debug.Print rs![EmployeeName]
End Sub
Private Sub cmdSearch_Click()
Dim strSQLHead As String
Dim strSQLWhere As String
Dim strSQLOrderBy As String
Dim strSQL As String
Dim strJoin As String
strJoin = " AND "
strSQLHead = "SELECT * FROM tblEmployee "
If Len(Me.txtEmployeeName & vbNullString) Then
If (Me.chkLike) Then
strSQLWhere = "WHERE [EmployeeName] Like " & Chr$(39) & "*" & _
Me.txtEmployeeName & "*" & Chr$(39)
Else
strSQLWhere = "WHERE [EmployeeName] = " & Chr$(39) & _
Me.txtEmployeeName & Chr$(39)
End If
strSQLWhere = strSQLWhere & strJoin
End If
If Len(Me.txtDOBStart & vbNullString) Then
If Len(strSQLWhere) = 0 Then
strSQLWhere = "WHERE "
End If
If Len(Me.txtDOBEnd & vbNullString) Then
strSQLWhere = strSQLWhere & "[EmployeeDOB] Between #" & Me.txtDOBStart & _
"# AND #" & Me.txtDOBEnd & "#"
Else
strSQLWhere = strSQLWhere & "[EmployeeDOB] >= #" & Me.txtDOBStart & "#"
End If
strSQLWhere = strSQLWhere & strJoin
End If
If Len(Me.cboPosition & vbNullString) Then
If Len(strSQLWhere) = 0 Then
strSQLWhere = "WHERE "
End If
strSQLWhere = strSQLWhere & "[EmployeePosition] = " & Me.cboPosition
strSQLWhere = strSQLWhere & strJoin
End If
If Len(strSQLWhere) Then
strSQLWhere = Left$(strSQLWhere, Len(strSQLWhere) - (Len(strJoin) - 1))
End If
strSQLOrderBy = "ORDER BY "
Select Case Me.fraOrderBy
Case 1
strSQLOrderBy = strSQLOrderBy & "[EmployeeName]"
Case 2
strSQLOrderBy = strSQLOrderBy & "[EmployeeDOB]"
Case 3
strSQLOrderBy = strSQLOrderBy & "[EmployeePosition]"
End Select
strSQL = strSQLHead & strSQLWhere & strSQLOrderBy
Me.fsubEmployee.Form.RecordSource = strSQL
End Sub