1

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

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

截图 1 截图 2

4

3 回答 3

1

此代码获取 column 中的前 100 个单元格,A按空格拆分其内容,并将其粘贴到 columnB

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

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

于 2019-04-15T08:56:15.133 回答
1

我知道核心挑战是除以 2+ 个空格,而不是除以 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)
于 2019-04-15T09:40:16.800 回答
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
于 2019-04-15T10:48:27.970 回答