【问题标题】:Split text separated by multiple blank spaces into multiple columns将由多个空格分隔的文本拆分为多列
【发布时间】:2019-10-29 09:37:10
【问题描述】:

我需要将一些单元格的文本内容拆分成多列。

单元格内的文本不遵循精确的模式(例如逗号、分号...),但文本片段由多个空格分隔。这是一个例子:

你好,我的名字是 Andrea(多个空格)我很好(多个空格)你呢?

我想将我的文本分成三列(一列包含Hi my name is Andrea,第二列包含I am good ...)。

句子之间的空格并不总是相同的(例如Andrea和I am good之间有5个空格,而good和what about you之间有7个空格)。

我认为在遇到多个空格时拆分文本可能是个好主意。这是我试过的代码:

Sub NameSplit()

    Dim txt As String
    Dim i As Integer
    Dim FullName As Variant
    Dim x As String, cell As Range

    txt = ActiveCell.Value

    FullName = Split(txt, " ")

    For i = 0 To UBound(FullName)

        Cells(1, i + 1).Value = FullName(i)

    Next i

End Sub

【问题讨论】:

  • 欢迎来到 SO!当您提出问题时,请尝试添加最少的内容:输入样本、预期输出样本、您尝试了什么、研究以及您卡在哪里。你尝试了什么?
  • 用2个空格作为分隔符怎么样?
  • @SJR 但只能与Trim$() 结合使用,否则如果有奇数个空格,您将留下空格。

标签: excel vba split cell


【解决方案1】:

您可以使用以下内容将字符串拆分为多列

Dim rng As Range
Dim txt As String
Dim FullName() As String
Dim i As Long, colOffset As Long

Set rng = ActiveCell
txt = rng.Value2

FullName = Split(txt, String(2, " "))

For i = LBound(FullName) To UBound(FullName)
    If Not WorksheetFunction.Trim(FullName(i)) = vbNullString Then
        Debug.Print WorksheetFunction.Trim(FullName(i))
        colOffset = colOffset + 1
        rng.Offset(0, colOffset).Value2 = WorksheetFunction.Trim(FullName(i))
    End If
Next i

输出:

  • 嗨,我叫安德里亚
  • 我很好
  • 你呢?

【讨论】:

    【解决方案2】:

    它可以使用双空格作为分隔符。结合使用Trim$() 删除剩余空格(例如,奇数个空格被赋予双倍空格作为分隔符导致以下数据开头的剩余空格)。

    Option Explicit
    
    Public Sub NameSplit()
        Dim Cell As Range
        Set Cell = Range("A1")
    
        Dim SplitData() As String
        SplitData = Split(Expression:=Cell.Value, Delimiter:="  ") 'double space as delimiter
    
        Dim i As Long, j As Long
        For i = LBound(SplitData) To UBound(SplitData)
            If Trim$(SplitData(i)) <> vbNullString Then
                Cell.Offset(ColumnOffset:=j).Value = Trim$(SplitData(i))
                j = j + 1
            End If
        Next i
    End Sub
    

    会转

    进入

    如果您需要对多个单元格执行此操作,请将代码包装到一个循环中。

    For iRow = 1 To LastRow
        Set Cell = Cells(iRow, "A")
        ' …
    Next iRow
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多