VBA Excel 根据最后一个逗号将字符串分开

问题描述

我想在地址和邮政编码之间拆分 Excel 中的字符串。我想单独保留邮政编码。

通过选择选项 - 数据 - 文本到列 - 分隔 - 逗号分隔 - 整个字符串被 4 部分分割,因为出现 3 个逗号。

1 - 21 Willow Court,1192 Christchurch Road,Bournemouth,BH7 6EG

我发现,它可以在 VBA Excel 中完成。

下面有几种方法

Excel VBA- remove part of the string

https://www.thespreadsheetguru.com/the-code-vault/2014/2/28/remove-last-character-from-string

How to delete last character in a string with VBA?

Removing last characters vba

How to i remove a text after '*' or '-' character using VBA in excel?

我准备了如下的 VBA 代码

   Sub Textremove()
   Dim c As Variant
   For Each c In Range("D1:D100")
   c.Value = Left(c.Value,InStr(c.Value,",") - 1)
   Next c
   End Sub

我只收到:

1 - 21 Willow Court

错误 Invalid procedure call or argument,调试以下行:

     c.Value = Left(c.Value,") - 1)

所以细分发生在第一个逗号之后,而不是最后一个

我找到了有关此错误的答案:

invalid procedure call or argument left

当我的代码如下所示时:

  Sub Textremove()
  Dim c As Variant
  For Each c In Range("D1:D100")
  If InStr(c.Value,") > 0 Then
  c.Value = Left(c.Value,") - 1)
  End If
  Next c
  End Sub

然后错误不再发生,但直到第一个逗号而不是最后一个逗号我仍然得到这些东西。

当我稍微更改代码时:

 Sub Textremove()
 Dim c As Variant
 For Each c In Range("D1:D100")
 If InStr(c.Value,") > 0 Then
 c.Value = Right(c.Value,"))
 End If
 Next c
 End Sub

我从右边得到 2 个句子

伯恩茅斯,BH7 6EG

不是固定的,会根据字符串的总长度而变化。

如何接收字符串直到最后一个逗号而不是第一个逗号? 如何分别在地址和邮政编码之间拆分整个字符串?

这里有一个很好的例子:

https://trumpexcel.com/vba-split-function/

  Sub CommaSeparator()
  Dim TextStrng As String
  Dim Result() As String
  Dim displayText As String
  Dim i As Long
  TextStrng = Sheets("Final").Range("D1")
  Result = Split(TextStrng,1)
  For i = LBound(Result()) To UBound(Result())
  displayText = displayText & Result(i) & vbNewLine
  Next i
  MsgBox displayText
  End Sub

它确实拆分了整个地址,但仍然从第一个逗号开始计算。

解决方法

在我的情况下是有效的。我刚刚添加了 UBound(Result())-1。

Sub CommaSeparator()
  Dim TextStrng As String
  Dim Result() As String
  Dim DisplayText As String
  Dim i As Long
  TextStrng = Sheets("Final").Range("D1")
  Result = Split(TextStrng,",")
  For i = LBound(Result()) To UBound(Result()) - 1
  DisplayText = DisplayText & Result(i) & vbNewLine
  Next i
  MsgBox DisplayText
End Sub
,

如果您需要 VBA,可以使用:

Sub Test()

Dim str As String
Dim arr As Variant

str = "1 - 21 Willow Court,1192 Christchurch Road,Bournemouth,BH7 6EG"
arr = Split(StrReverse(Replace(StrReverse(str),"|",1)),"|")
    
End Sub

我通过 StrReverse() 反转整个字符串,然后使用 Replace() 仅用管道符号替换第一个逗号(注意 Count 参数的使用),反转字符串返回并使用 Split()。这将返回:


另一种方法是使用工作表函数 REPLACE() 而不是 VBA 函数,后者被称为相同的函数。

Sub Test()

Dim str As String: str = "1 - 21 Willow Court,BH7 6EG"
Dim arr As Variant

arr = Split(Application.Replace(str,InStrRev(str,"),1,"|"),"|")

End Sub

现在的主要区别在于,Application.Replace 确实采用了一个参数来开始替换, 无需 剪切前面的文本。我们可以使用 InstrRev() 找到我们的起始位置。


两个选项都返回:

enter image description here


只是为了好玩,我会使用正则表达式解决方案:

Sub Test()

Dim str As String: str = "1 - 21 Willow Court,BH7 6EG"
Dim arr As Variant

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "^.*(?=,)|[^,]+$"
    Set arr = .Execute(str)
End With

End Sub

这将返回一个“MatchCollectionObject”,您可以在其中调用您的结果:arr(0)arr(1)。模式的一点解释:

  • ^ - 起始字符串锚点。
  • .* - 除换行符之外的任何内容的贪婪匹配:
  • (?=,) - 逗号的正前瞻。
  • | - 或匹配:
  • [^,]$ - 除了逗号之外的任何东西,直到结束字符串锚点。

查看在线demo

enter image description here

,

使用 Split 返回的数组重建您喜欢的字符串,例如:

Sub DoSplit()

s = "1 - 21 Willow Court,BH7 6EG"
a = Split(s,")
finalString = a(0) & a(1) & a(2) & "," & a(3)
MsgBox finalString

End Sub
,

我以不同的 2 步方式对此进行了排序。

首先,我使用这里的公式拆分了整个地址:

Split address field in Excel

Sub Split()
  Dim MyArray() As String
  Dim Ws As Worksheet
  Dim lRow As Long,i As Long,j As Long,c As Long

  '~~> Change this to the relevant sheet name
  Set Ws = ThisWorkbook.Sheets("Final")

  With Ws
    lRow = .Range("E" & .Rows.Count).End(xlUp).Row

    For i = 1 To lRow
        If InStr(1,.Range("E" & i).Value,vbTextCompare) Then
            MyArray = Split(.Range("E" & i).Value,")
            c = 1
            For j = 0 To UBound(MyArray)
                .Cells(i,c).Value = MyArray(j)
                c = c + 1
            Next j
        End If
      Next i
   End With
 End Sub

接下来,我使用这个提示合并了我需要的内容:

Excel macro to concatenate one row at a time to end of file

Sub Merge()
Dim LastRow As Long
Dim Ws As Worksheet

Set Ws = Sheets("Final")

LastRow = Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row

'~~> If your range doesn't have a header
Ws.Range("H1:H" & LastRow).Formula = "=A1&B1&C1"

'~~> If it does then
Ws.Range("H2:H" & LastRow).Formula = "=A2&B2&C2"
End Sub

最后,我收到了:

1 - 10 Haviland Court 104 Haviland Road Bournemouth