Question : Using A Variable In VBA SELECT Statement

I have a function that is called from my form.  I am hard coding a variable into the function simply for testing will implement after the SELECT statement syntax is correct.  I need help with the syntax.  I use the following below and I receive error "Too few parameters. Expected 1"

The important part is the "sZone" variable in line;
 --->    sSql = sSql & "WHERE tblLocations.Zone=" & sZone & " "
If I remove that line, it works fine.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
Public Function GenerateRandomRecords(ByVal iNumber) As Boolean
    Dim sSql As String
    Dim sZone As String
       
    On Error Resume Next
    'Assume the worst
    
    GenerateRandomRecords = False
    sZone = "West"
    
    If iNumber <= 0 Then
        MsgBox "Invalid number of records to generate specified"
    Else
        'Build SQL
        sSql = "INSERT INTO tblAudits (Building, Location, Floor, LocationType, [Zone], DateSelected) "
        sSql = sSql & "SELECT TOP " & iNumber & " Building, Location, Floor, LocationType, [Zone], Now() "
        sSql = sSql & "FROM tblLocations "
        sSql = sSql & "WHERE tblLocations.Zone=" & sZone & " "
        sSql = sSql & "ORDER BY RND(ID);"
        
        Err.Clear
        CurrentDb.Execute sSql, dbFailOnError
        If Err.Number = 0 Then
            GenerateRandomRecords = True
        Else
            MsgBox Err.Description
        End If
    End If
End Function

Answer : Using A Variable In VBA SELECT Statement

Try changing this part:

sSql = sSql & "WHERE tblLocations.Zone=" & sZone & " "

to

Sql = sSql & "WHERE tblLocations.Zone=" & Chr(34) & sZone & Chr(34)

mx
Random Solutions  
 
programming4us programming4us