我正在尝试使用excel / VBA从文本文件读取数据。但是,当我导入文件时,所有单词都在同一列中。在保留表格布局的同时,文本是从PDF生成的。因此,单词是用空格分隔的,但间距不一致。我希望代码在单元格中运行并分隔单词。但是对于细胞来说,有两件事是正确的
答案 0 :(得分: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 :(得分:1)
我知道核心挑战是要用2个以上的空格分开,而不是一个。
尝试一下,这是否对您有帮助:
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)
答案 2 :(得分: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