跳过分割函数中的双逗号

问题描述 投票:0回答:3

我的字符串(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
access-vba
3个回答
1
投票

在拆分之前,你可以用一个(,,)替换double(,):

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
投票

因为你也可以使用三倍的逗号,只需忽略空条目:

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

1
投票

我认为最好的方法是在拆分之前“清理”你的字符串以删除额外的逗号。但是,正如@Gustaf所说,你可以连续使用2个以上的逗号。所以一个可能的解决方案是迭代删除额外的逗号,直到你没有。这样的函数看起来像这样:

' 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
© www.soinside.com 2019 - 2024. All rights reserved.