如何导入长度可变的文本文件以使用VBA精益求精并将其分为几列?

时间:2018-10-15 16:07:06

标签: excel vba excel-vba

这是我对这个社区的第一个问题。

我想知道如何使用VBA将长度可变的文本文件(从bash脚本中)导入Excel并将其拆分为几列。我正在学习使用VBA,目前还无法弄清楚。这就是我所拥有的:

脚本中的服务器列表:

Servers list from script

这是我在excel中需要的输出:

Servers arranged

VBA宏将添加“日”和“%空闲”字段。

从6到11的数字将被手动添加,因此没有问题。

在此先感谢大家!

1 个答案:

答案 0 :(得分:0)

也许类似的方法可以工作(取决于您的数据/服务器列表结构的不同)。

您需要将函数FILE_PATH(如下)中的splitTextFileByServer的值更改为计算机上的任意位置。

Option Explicit

Private Sub WriteServerListToSheet()
    Dim logsSplitByServer() As String
    logsSplitByServer = splitTextFileByServer()

    Dim interimArray() As String
    Dim outputArray() As Variant: ReDim outputArray(1 To 8, 1 To 2)

    With ThisWorkbook.Worksheets("Sheet1").Range("A1")

        Dim serverIndex As Long
        Dim readIndex As Long
        Dim outputColumnOffset As Long

        For serverIndex = LBound(logsSplitByServer) To UBound(logsSplitByServer)
            interimArray = VBA.Strings.Split(logsSplitByServer(serverIndex), vbNewLine, -1, vbBinaryCompare)
            If (UBound(interimArray) + 1) <> UBound(outputArray) Then ' (+1) as interimArray is 0-based
                ReDim outputArray(1 To (UBound(interimArray) + 2), 1 To 2) '(+2) as 0-based and we want a row for headers: Day, %Idle
            End If

            ' Assume first item in interimArray is: server***
            outputArray(1, 1) = interimArray(LBound(interimArray))
            outputArray(2, 1) = "Day"
            outputArray(2, 2) = "%Idle"

            For readIndex = (LBound(interimArray) + 1) To UBound(interimArray)
                outputArray(2 + readIndex, 2) = interimArray(readIndex) ' (2 + ... as we want to skip first 2 rows
            Next readIndex

            .Offset(0, outputColumnOffset).Resize(UBound(outputArray, 1), UBound(outputArray, 2)).Value2 = outputArray
            outputColumnOffset = outputColumnOffset + 3 ' Change this if you decide to add columns
        Next serverIndex

    End With

End Sub

Private Function splitTextFileByServer() As String()
    Const FILE_PATH As String = "C:\Users\USER\Desktop\serverslist.txt"

    If Len(VBA.FileSystem.Dir$(FILE_PATH)) = 0 Then
        MsgBox ("No file exists at: " & FILE_PATH)
        Exit Function
    End If

    Dim fileContents As String
    ' Read file into memory; assumes it will fit.
    Open FILE_PATH For Binary Access Read As #1
    fileContents = VBA.Strings.Space$(LOF(1))
    Get #1, 1, fileContents
    Close #1

    Dim outputArray() As String
    outputArray = VBA.Strings.Split(fileContents, "########################################" & vbNewLine, -1, vbBinaryCompare)

    splitTextFileByServer = outputArray
End Function

如果它不起作用,请告诉我为什么/输出有问题。