使用SQL时遇到IF条件问题

时间:2016-08-04 22:13:21

标签: sql vba excel-vba access-vba excel

我似乎无法得到这个IF语句来进入Call Expiry部分,因此我只能假设我的病情有问题。

我正在尝试从访问表中获取合同状态 投资数据 WHERE 客户编号客户编号。 (电子表格中只有1个客户编号)。

我的逻辑是否有问题或SELECT语句是否返回不是字符串的内容?

感谢任何帮助,谢谢。

 If ("SELECT [Contract Status] FROM [Investment Data] WHERE [Customer Number] =(" & "SELECT [Customer Number] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh & ")") = "Current" Then
        expiryPrompt = MsgBox("A previous entry from the same contract is currently active, would you like to expire current active contract?", vbYesNo, "Confirmation")
        Call Expiry
        Exit Sub
    Else
        MsgBox ("Entry has been entered into the database.")
        cN.Execute ssql
        Exit Sub
    End If

编辑1:在尝试存储SELECT时,我有以下

Dim cdb As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim temp As String

strSQL = "SELECT [Contract Status] FROM [Investment Data] WHERE [Customer Number] =(" & _
"SELECT [Customer Number] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh & ")"

Set cdb = DAO.OpenDatabase(dbPath)
Set rst = cdb.OpenRecordset(strSQL)
temp = rst

我知道Recordset的返回值不是String我只是不知道如何将它存储在变量中。

1 个答案:

答案 0 :(得分:0)

您需要将值放入某个内容中,以便在if语句中进行比较。如果我明白你想要什么,那就试一试吧。我还假设您将在SQL语句中获得一个结果。

    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    conn.Open sConnString
    Set rs.ActiveConnection = conn


    strSQL = "SELECT [Contract Status] FROM [Investment Data] WHERE
     [Customer Number] =(" & "SELECT [Customer Number] FROM
      [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh & ")"

    rs.Open strSQL
        If Not rs.EOF Then xx = rs.GetRows Else 'do you code for not getting result 
    rs.Close

    If xx(0, 0) = "Current" Then
        expiryPrompt = MsgBox("A previous entry from the same contract is currently active, would you like to expire current active contract?", vbYesNo, "Confirmation")
        Call Expiry
        Exit Sub
    Else
        MsgBox ("Entry has been entered into the database.")
        cN.Execute ssql
        Exit Sub
    End If

我也没有在if语句中修改你的代码,以便按照我访问数据库的方式。

在答案中回答你的问题。 结果将转换为变量。所以访问多个行或列,你需要做这样的事情。

获取行

        For i = 0 To 9

          Cells(i + 1, 1) = x(0, i)

        Next i

获取列,

        For i = 0 To 9

          Cells(1, i + 1) = x(i, 0)

        Next i