Dim cn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Private Sub Command1_Click()
    Dim txtSQL As String
    Dim dd(3) As Boolean
    Dim sMeg As String
    Set cn = New ADODB.Connection
    Set rst = New ADODB.Recordset
    cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ssglbase;Data Source=虞毓-PC"
    cn.Open
    txtSQL = "select * from user_SS "
    If Check1.Value Then
        If Trim(txtdong.Text) = "" Then
            sMeg = "栋号不能为空"
            MsgBox sMeg, vbOKOnly + vbExclamation, "警告"
            txtdong.SetFocus
            Exit Sub
        Else
            If Not IsNumeric(Trim(txtdong.Text)) Then
                MsgBox "请输入栋号数字!", vbOKOnly + vbExclamation, "警告"
                Exit Sub
                txtdong.SetFocus
            End If
            dd(0) = True
            txtSQL = txtSQL & "栋号 = '" & Val(Trim(txtdong.Text)) & "'"
        End If
    End If
    
    If Check2.Value Then
        If Trim(txtroom.Text) = "" Then
            sMeg = "寝室号不能为空"
            MsgBox sMeg, vbOKOnly + vbExclamation, "警告"
            txtroom.SetFocus
            Exit Sub
        Else
            dd(1) = True
            If dd(0) Then
                txtSQL = txtSQL & "and 寝室号 = '" & Trim(txtroom.Text) & "'"
            Else
                txtSQL = txtSQL & "寝室号 = '" & Trim(txtroom.Text) & "'"
            End If
        End If
    End If
    
    If Check3.Value Then
        If Trim(txtcollege.Text) = "" Then
            sMeg = "学院不能为空"
            MsgBox sMeg, vbOKOnly + vbExclamation, "警告"
            txtcollege.SetFocus
            Exit Sub
        Else
            dd(2) = True
            If dd(0) Or dd(1) Then
                txtSQL = txtSQL & "and 学院= '" & Trim(txtcollege.Text) & "'"
            Else
                txtSQL = txtSQL & "学院= '" & Trim(txtcollege.Text) & "'"
            End If
        End If
    End If
    
    If Not (dd(0) Or dd(1) Or dd(2)) Then
        MsgBox "请设置查询方式!", vbOKOnly + vbExclamation, "警告"
        Exit Sub
    End If
    
    
    txtSQL = txtSQL & " order by 栋号,寝室号"
    rst.CursorLocation = adUseClient
    rst.Open txtSQL, cn, 1, 3
    Set DataGrid1.DataSource = rst
    rst.Close
End SubPrivate Sub Command2_Click()
Unload Me
frmMain.Show
End SubPrivate Sub Form_Unload(Cancel As Integer)
cn.Close
End Sub
提示:  实时错误‘-2147217900(80040e14)
        第1行:’=‘附近有语法错误

解决方案 »

  1.   

    好像在SQL语句中没发现where,这样试试:
    txtSQL = "select * from user_SS where "
      

  2.   

     If Check2.Value Then 和 If Check3.Value Then  里面的  txtSQL = txtSQL & "and ...“
    的and,学院,寝室号   前面都加一个空格
      

  3.   

    你没有加 where 关键字啊 txtSQL = "select * from user_SS where" 
      

  4.   

    加了where后面记得加个空格哦....就不用来再次提问啦.~~
      

  5.   

    txtSQL = txtSQL & " order by 栋号+寝室号"
      

  6.   

    可以运行了  
    谢谢各位的帮忙
    这个程序还要把rst.Close删了才运行起来的,带过!