在拆分功能中跳过双逗号

时间:2019-04-21 17:07:27

标签: access-vba

我的字符串(strSQL)值为1,2,3,,4,并且由于双逗号(,,),我的结果显示3到4之间为空白。我的代码如下:-

strParts = Split(strSQL, ", ")
        For intCounter = LBound(strParts()) To UBound(strParts())
            Me.Controls("cmd" & intCounter).Visible = True
            Me.Controls("cmd" & intCounter).Caption = strParts(intCounter)                
        Next intCounter

3 个答案:

答案 0 :(得分:1)

在拆分之前,您可以将双精度(,,)替换为单个(,):

strSQL = Replace(strSQL, ",,", ",")

或者您使用单独的索引:

strParts = Split(strSQL, ",")

Dim index As Long
Dim counter As Long
For index = LBound(strParts()) To UBound(strParts())
    If Len(Trim(strParts(index))) > 1 Then
        counter = counter + 1
        Me.Controls("cmd" & counter).Visible = True
        Me.Controls("cmd" & counter).Caption = strParts(index)
    End If
Next index

答案 1 :(得分:1)

您也可以将逗号加三倍,因此只需忽略空白条目:

Dim Part As String

strParts = Split(strSQL, ",")

For intCounter = LBound(strParts()) To UBound(strParts())
    Part = Trim(strParts(intCounter))
    If Part <> "" Then
        Me.Controls("cmd" & Part).Visible = True
        Me.Controls("cmd" & Part).Caption = Part
    Else
        Me.Controls("cmd" & Part).Visible = False
    End If
Next

答案 2 :(得分:1)

我认为做到这一点的最佳方法是对字符串进行“消毒”以在拆分之前删除多余的逗号。但是,正如@Gustaf所指出的,您可以连续使用两个以上的逗号。因此,一种可能的解决方案是迭代删除多余的逗号,直到没有为止。这样的功能看起来像这样:

' given a string that contains consecutive commas (e.g. abc,,def,,,ghi),
' removes all but the first commas (e.g. abc,def,ghi
Public Function RemoveDuplicateCommas(ByVal s As String) As String
    Do While InStr(1, s, ",,", vbBinaryCompare) > 0
        s = Replace(s, ",,", ",")
    Loop

    RemoveDuplicateCommas = s
End Function

要使用此功能,请执行以下操作:

strSQL = "1,2,3,,4,,,5"
strSQL = RemoveDuplicateCommas(strSQL)
?strSQL
1,2,3,4,5
?join(split(strsql, ","), ",")
1,2,3,4,5