【问题标题】:VBA Excel split the string apart based on the last commaVBA Excel 根据最后一个逗号拆分字符串
【发布时间】:2023-03-27 04:40:01
【问题描述】:

我想在 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 柳苑

和错误无效的过程调用或参数,调试以下行:

     c.Value = Left(c.Value, InStr(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, InStr(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, InStr(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

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

【问题讨论】:

  • 您不需要 VBA。你有什么版本的Excel?顺便说一句,对彻底的问题表示敬意!很好的研究。
  • 嗨,我知道,我不需要 VBA,因为它有很多可用的 excel 公式提示。但是我正在自动化一些东西,所以我担心这次我需要 VBA。

标签: excel vba street-address


【解决方案1】:

就我而言,这是可行的。我刚刚添加了 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

【讨论】:

    【解决方案2】:

    如果您需要 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 参数),将字符串反转并使用@987654323 @。这返回:


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

    Sub Test()
    
    Dim str As String: str = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
    Dim arr As Variant
    
    arr = Split(Application.Replace(str, InStrRev(str, ","), 1, "|"), "|")
    
    End Sub
    

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


    两个选项都返回:


    只是为了好玩,我会加入一个正则表达式解决方案:

    Sub Test()
    
    Dim str As String: str = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, 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

    【讨论】:

    • 我试了两个你的代码,没有错误,但完全没有反应。我认为我需要的不是固定字符串,而是: Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Final") Dim str As String: str = ws.Range("A" & ws.Rows.Count).End (xlUp).Row
    • 您已经找到了一种遍历单元格的方法。现在实现上述内容应该不会太难了。您首先尝试将所有内容拆分并扔到单独的单元格中,这只是多余的。 @MKR。
    【解决方案3】:

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

    Sub DoSplit()
    
    s = "1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG"
    a = Split(s, ",")
    finalString = a(0) & a(1) & a(2) & ", " & a(3)
    MsgBox finalString
    
    End Sub
    

    【讨论】:

      【解决方案4】:

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

      首先,我使用此处的公式拆分整个地址:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多