我有多行字符串,包括文本和数字。我想对除了第一个和最后一个部分之外的空格分隔的列进行文本处理。
如果我将文本运行到由空格分隔的列,那么它会拆分我不想拆分的字符串。
示例:
Quarterly Performance Numbers 999,999.99 12.00 1.00 2.00 3.00 4.00 Dec 09, 2013
变为:
Quarterly|Performance|Numbers|999,999.99|12.00|1.00|2.00|3.00|4.00|Dec|09,|2013
我想要的是什么:
Quarterly Performance Numbers|999,999.99|12.00|1.00|2.00|3.00|4.00|Dec 09, 2013
问题是该部分的长度和字数不同(从3到6)。
有没有办法可以在VBA中围绕这两个字符串创建文本限定符?
Sub Macro3()
Dim i As Integer
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To LastRow
Cells(i, 2).Value = Mid(Cells(i, 1), 29, 37)
Cells(i, 3).Value = Right(Cells(i, 1), 12)
Cells(i, 1).Value = Left(Cells(i, 1), 37)
Next i
End Sub
答案 0 :(得分:1)
Sub Test()
Dim sContent, oMatch, arrParsed(), sResult
sContent = "Quarterly Performance Numbers 999,999.99 12.00 1.00 2.00 3.00 4.00 Dec 09, 2013"
arrParsed = Array()
With New RegExp ' Tools - References - add "Microsoft VBScript Regular Expressions 5.5" or use With CreateObject("VBScript.RegExp")
.Pattern = "(?:(?:[a-z ]+(?= )){3,6}|(?:-*[\d,.]+(?= ))|(?:[a-z]{3} \d{2}, \d{4}))"
.Global = True
.IgnoreCase = True
For Each oMatch In .Execute(sContent)
ReDim Preserve arrParsed(UBound(arrParsed) + 1)
arrParsed(UBound(arrParsed)) = oMatch.Value
Next
End With
' here you can use arrParsed
sResult = Join(arrParsed, ";")
MsgBox sResult
End Sub
答案 1 :(得分:0)
我想出了一种有效的方法。正如我被警告的那样,RegEx最终成为一个问题而非解决方案。我的方法并不漂亮,但它完成了工作。我通过删除空格后的字符串长度减去字符串的长度来计算空格数。空格中唯一的变量来自描述中的空格数,因此如果我从总空间中减去8个最小空格,我可以用它来用“;”替换第N个空格。我这样做了7次,我的所有列都以分隔的文本正确排列到列。感谢大家。对不起,如果我的解释很糟糕。
Sub Macro14()
Dim i As Long
Dim smaller As String
Dim spaces As Integer
Dim fixed As String
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To LastRow
smaller = Replace(Cells(i, 1), " ", "")
spaces = Len(Cells(i, 1)) - Len(smaller) - 8
fixed = Cells(i, 1).Value
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after desc
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after value
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after %age
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after first perf column
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after second perf column
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after third perf column
fixed = WorksheetFunction.Substitute(fixed, " ", ";", spaces) 'after fourth perf column/before the date
Cells(i, 1).Value = fixed
Next i
End Sub