如何在vba中的数组末尾正确连接字符串?

时间:2016-04-07 14:34:21

标签: sql arrays string vba concatenation

如何连接以下字符串以生成SQL语句?

Dim sql = "SELECT * FROM users with (nolock) WHERE"

    Dim sql2 = "(ownerID = '"

    For Each item In arrExcelValues

        sql2 = sql2 + item + "' or renterID = '" + item + "') or"

    Next

我需要它看起来像这样; SELECT * FROM users with (nolock) WHERE (ownerID = '12554' or renterID = '12554') or (ownerID = '32433' or renterID = '32433')

因此,当它到达数组的末尾时,它将不包含“或”。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

你可以修改我给你的问题的最后一个答案...... see here

但我已经为你做了

Sub test()

    Dim strQuery As String
    Dim strVals As String

    Dim rngTarget As Range
    Set rntTarget = Range("A1:A7")

    Dim varArr
    Dim lngRow As Long
    Dim myArray()
    varArr = rntTarget.Value2

    ReDim myArray(1 To UBound(varArr, 1))

    For lngRow = 1 To UBound(varArr, 1)
        myArray(lngRow) = varArr(lngRow, 1)
    Next

    strVals = "('" & Join$(myArray, "','") & "') "

    strQuery = "SELECT * FROM users WHERE "

    For lngRow = LBound(myArray) To UBound(myArray)
        strQuery = strQuery & "( owner = '" _
            & myArray(lngRow) + "' or renterID = '" _
            & myArray(lngRow) & "') or "
    Next

    strQuery = Left(strQuery, Len(strQuery) - 4)

    Debug.Print strQuery

End Sub