vba宏读取带有分隔和非分隔空格的字符串

时间:2015-03-24 20:30:11

标签: excel excel-vba access-vba vba

我有一个.txt文档,其表格信息如下

Recipient                    PanelSize                  NumberOfAlerts

Michigan Regional             42454                      15756
Wellcare                      21234                       8492
Michigan Patient Care          6789                       1056

我正在使用VBA宏来读取.txt文件并输入到Excel工作表中。

我主要与收件人有问题。收件人名称包含空格,因此使用

vDatavalues = Split(sLine, " ")

分隔收件人,如

Michigan|       |Patient|        |Care|

我不想要。

如何将我正在阅读的行格式化为3列正确地从表格中逐行读取?

编辑:以下是我尝试阅读的格式{。{3}}

的.txt文件示例

1 个答案:

答案 0 :(得分:3)

这有效:

Dim sLine As String
sLine = "Michigan Patient Care          6789                       1056"

'Remove all double spaces
Do While InStr(sLine, "  ") <> 0
    sLine = Replace(sLine, "  ", " ")
Loop

'Split using space delimiters
Dim splitLine() As String
splitLine = Split(sLine, " ")

'Collect recipient pieces 
'(i.e. all pieces but the last two, which we know are PanelSize and NumberOfAlerts)
Dim splitRecipient() As String
ReDim splitRecipient(0 To UBound(splitLine) - 2)
Dim i As Long
For i = 0 To UBound(splitRecipient)
    splitRecipient(i) = splitLine(i)
Next i

'Join recipient pieces
MsgBox "Recipient: " & Join(splitRecipient, " ") & vbCrLf & _
    "PanelSize: " & splitLine(UBound(splitLine) - 1) & vbCrLf & _
    "NumberOfAlerts: " & splitLine(UBound(splitLine))

enter image description here

但实际上,如果你的文件是固定宽度格式,列总是具有相同的宽度并用空格填充,那么它就容易多了。在您的示例中,第一列看起来像30个字符宽,第二列看起来是27.所以在这种情况下,您可以这样做:

Dim sLines() As String
ReDim sLines(1 To 3)
sLines(1) = "Michigan Regional             42454                      15756"
sLines(2) = "Wellcare                      21234                       8492"
sLines(3) = "Michigan Patient Care          6789                       1056"

Dim iLine As Long
For iLine = LBound(sLines) To UBound(sLines)
    MsgBox "Recipient: " & Trim(Mid(sLines(iLine), 1, 30)) & vbCrLf & _
        "PanelSize: " & Trim(Mid(sLines(iLine), 31, 27)) & vbCrLf & _
        "NumberOfAlerts: " & Trim(Mid(sLines(iLine), 58))
Next iLine

然后将第一行解析为:

enter image description here