如何从单列中分离单词

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

我试图使用excel / VBA从文本文件中读取数据。但是,当我导入文件时,所有单词都在同一列中。文本是从PDF生成的,同时保留了表格布局。所以单词是空格分隔的,但间距不一致。我希望代码能够遍历单元格并将单词分开。然而,对于细胞来说,有两件事是真的

  1. 单个单词有一个间距
  2. 单词由两个或多个空格分隔

Screenshot 1 Screenshot 2

vba text-to-column
3个回答
1
投票

此代码获取列A中的前100个单元格,按空间分割其内容,并将其粘贴到列B

Dim A_row As Integer, B_row as Integer, i As Integer, words()
For A_row = 1 To 100' Last row t o consider
    words = Split(Range("A" & A_row), " ")
    For i = LBound(words) To UBound(words)
        B_row = B_row + 1
        Range("B" & B_row) = words(i)
    Next i
Next A_row

我相信你可以得到要点,并根据你的需要进行修改


1
投票

我知道核心挑战是分成两个以上的空格,而不是一个空格。

试试这是否有助于你:

Const marker As String = "[!°$(])"
Dim rx, s As String, t As String, parts
Set rx = CreateObject("vbscript.regexp")

s = "One Cell   Red  Green"

rx.Pattern = " {2,}" ' match two or more spaces
rx.Global = True ' find all, not only the first match
t = rx.Replace(s, marker)

parts = Split(t, marker)
MsgBox Join(parts, vbCrLf)

1
投票

谢谢@Uri Goren @Kenusemau。为其他寻找相同问题的人发布答案。

Sub Macro2()
Const marker As String = "#$"
Dim rx, s As String, t As String, parts
Set rx = CreateObject("vbscript.regexp")

For A_row = 1 To 2 ' Last row t o consider
    s = Range("A" & A_row)
        rx.Pattern = " {2,}" ' match two or more spaces
        rx.Global = True ' find all, not only the first match
        t=rx.Replace(s, marker)
        Range("B" & A_row).Value = t
        'parts = Split(t, marker)
        'Range("B" & A_row).Value = Join(parts, vbCrLf)
                Range("B" & A_row).Select
                Selection.TextToColumns _
                Destination:=Range("C" & A_row), _
                DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, _
                ConsecutiveDelimiter:=False, _
                Tab:=True, _
                Semicolon:=False, _
                Comma:=False, _
                Space:=False, _
                Other:=True, _
                OtherChar:="#$"
Next A_row
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.