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

标签 excel ms-access 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 列,从表格中逐行正确读取?

编辑:这是我尝试读取和格式化的 .txt 文件的示例 TEST.txt

最佳答案

这有效:

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

关于excel - vba 宏读取带分隔和非分隔空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242296/

相关文章:

vba - 重命名文件夹 vba 中的文件

vba - 插入工作表

json - 打开网页,全选,复制到工作表

excel - 工作簿是只读的,再试一次

python - 调用 Python 文件后 Excel CSV 输出出现错误

java - "incompatible datatypes in combination"查询日期值时出错

ms-access - VBA MS Access : Function in a Private Sub to access Sub variables

vba - Excel UDF - 获得值(value)!错误并且不知道为什么

mysql - 如何在mysql数据库中自动导入xlsx文件

sql - MS ACCESS : selecting only one record per "person" per date 中的子查询