VBA - 多行文本框到SQL IN语句

时间:2015-10-09 20:13:25

标签: vba excel-vba excel

正如标题所述,我有一个多行文本框,我需要将多个值复制/粘贴到(每行都存在)并让它们变成一个数组,这将构建一个SQL In语句。我已经使用一个完美的列表框来做这个,但是无法弄清楚用文本框来做它

我的文本框名为fo​​rm_payment_inv,启用了多行。

复制/粘贴示例

1234
5678

所需的输出将是

IN ('1234','5678')

1 个答案:

答案 0 :(得分:1)

你可以这样做:

Private Sub CommandButton1_Click()
    ' Split the text box's multiple lines by \r\n
    Dim myarr() As String
    myarr() = Split(TextBox1.Text, vbCrLf)

    ' Find total items contained in the array and put single quotes around them
    Dim TotalItems As Integer
    TotalItems = UBound(myarr)        
    Dim I As Integer
    For I = 0 To TotalItems
        myarr(I) = "'" & myarr(I) & "'"
    Next I

    ' create the IN statement
    Dim SQL_IN As String
    SQL_IN = Join(myarr, ",")
    MsgBox SQL_IN
End Sub

结果将是'1234','5678'