Excel + VBA:Userfrom字符串Deal(Order)编号解析

时间:2017-03-28 09:24:52

标签: excel vba excel-vba

我正在尝试制作一个连接旧版访问数据库的完整功能报告文件。我需要构建一个Userform,用户可以输入交易(订单)编号,就像我们可以在打印对话框中添加页面一样。

到目前为止,我发现以下问题给了我部分答案: How to Parsing Full String and split into several String in Excel VBA?

我可以使用Split(string)方法在以“,”分隔时获取各种交易号。

但是,我也需要From to TO交易号码选项。

所以,如果用户输入String1 =“10001 - 10050,201111,201115”

然后我需要输出

Deal_Line.Deal_Number> = 10001和Deal_Line.Deal_Number< = 10050 和Deal_Line.Deal_Number = 20111和Deal_Line.Deal_Number = 20115。

我可以根据我的要求改进SQL String,我想知道是否有办法使用两个deliminator。

2 个答案:

答案 0 :(得分:1)

你可以使用这个助手功能:

Function ProcessString(strng1 As String) As String
    Dim sqlStrng As String
    Dim strng As Variant, limits As Variant

    For Each strng In Split(strng1, ",")
        limits = Split(strng, "-")
        If UBound(limits) = 0 Then
            sqlStrng = sqlStrng & "Deal_Line.Deal_Number = " & limits(0) & "|"
        Else
            sqlStrng = sqlStrng & "Deal_Line.Deal_Number >= " & limits(0) & " And Deal_Line.Deal_Number <= " & limits(1) & "|"
        End If
    Next
    ProcessString = WorksheetFunction.Trim(Join(Split(Left(sqlStrng, Len(sqlStrng) - 1), "|"), " And "))
End Function

在你的&#34; main&#34;进行测试/解释代码为:

Sub main()

    MsgBox ProcessString("10001 - 10050, 20111 , 20115")

End Sub

答案 1 :(得分:1)

扩展@ user3598756回答,(这完全符合您的要求)并解释您的要求我提出以下内容:

Function ProcessString(strng1 As String, fieldname As String) As String
    Dim sqlStrng As String
    Dim strng As Variant, limits As Variant

    For Each strng In Split(strng1, ",")
        limits = Split(strng, "-")
        If UBound(limits) = 0 Then
            sqlStrng = sqlStrng & "[FIELD] = " & limits(0) & "|"
        Else
            sqlStrng = sqlStrng & "([FIELD] >= " & Trim(limits(0)) & " And [FIELD] <= " & Trim(limits(1)) & ")|"
        End If
    Next
    ProcessString = Replace(WorksheetFunction.Trim(Join(Split(Left(sqlStrng, Len(sqlStrng) - 1), "|"), " Or ")), "[FIELD]", fieldname)
End Function

测试线将是:

MsgBox ProcessString("10001 - 10050, 20111 , 20115","Deal_Line.Deal_Number")

这会产生一个我认为更有可能是您真正想要的输出 - 使用OR代替AND作为初学者,添加OR工作所需的括号正确并允许多个表/字段名称。 然后,也许我误解了你的要求 - 我只是看不出有什么用AND将是一个字段。