首页 > 解决方案 > 使用 VBA 脚本制作平面文件 - 删除空白行并处理更多卷?

问题描述

对 VBA 来说是全新的,就在这里。我正在尝试编写一个脚本,用于将 Excel 电子表格中的数据转换为平面文件 (.txt) 以加载到 ERP 中。

我已经拼凑了下面的脚本,但是有两个问题我希望有人能指出我解决的正确方向。

  1. 平面文件的数据底部有空白行。
  2. 该脚本似乎无法处理大量。我在大约 30,000 行标记处遇到溢出错误。

这是我到目前为止所得到的,如果它很混乱,请道歉:


    Private Sub CommandButton2_Click()

    ' Turns all the numbers and stuff into a flat file!!!

    ' Defines things.
    Dim myPRFile As String
    Dim TextFile As Integer
    Dim FileContent As String
    Dim rng As Range
    Dim cellValue As Variant
    Dim i As Integer
    Dim j As Integer
    
    ' Defines the file to use and the part of the spreadsheet to copy from.
    myPRFile = "C:\Users\my.folder\Documents\Docs\Logics\flat.txt"
    Range("B2").CurrentRegion.Select
    Set rng = Selection
    
    ' Loops through the data puts it in the text file.
    Open myPRFile For Output As #1
    For i = 1 To rng.Rows.Count
        For j = 1 To rng.Columns.Count
    cellValue = rng.Cells(i, j).Value
    If j = rng.Columns.Count Then
        Print #1, cellValue
    Else
        Print #1, cellValue; "|";
    End If
        Next j
    Next i
    Close #1
    
    ' Takes the spaces out of the file.
    TextFile = FreeFile
    
    Open myPRFile For Input As TextFile
    FileContent = Input(LOF(TextFile), TextFile)
    Close TextFile
    
    FileContent = Replace(FileContent, " ", "")
    
    Open myPRFile For Output As TextFile
    Print #TextFile, FileContent
    Close TextFile
    
    ' Opens the finished product.
    Dim fso As Object
    Dim sfile As String

    Set fso = CreateObject("shell.application")
    sfile = "C:\Users\my.folder\Documents\Docs\Logics\flat.txt"
    fso.Open (sfile)

End Sub

它按原样非常有用,但如果可能的话,我很想破解最后几件事。

标签: excelvbatextflat-file

解决方案


推荐阅读