一次写多行而不是使用WriteLine来提高性能?

时间:2015-07-02 11:52:48

标签: excel vba csv

我创建了一个使用自定义分隔符创建CSV文件的功能(例如:&#34 ;;"或" - "而不是",&#34 ;)

我有一个FOR循环,将我的范围的每一行写入CSV,但是当在远程服务器中创建CSV时,逐行执行它非常慢。我的目的是创建一个包含循环中所有文件的字符串,并打印到它外面的CSV。

是否可以这样做?

这就是我现在正在做的事情:

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(FilePath)
ColsCount = wb.Sheets(1).UsedRange.Columns.Count
RowsCount = wb.Sheets(1).UsedRange.Rows.Count

With wb.Sheets(1)
    For r = 1 To RowsCount
        Line = Join(Application.Transpose(Application.Transpose(.range(.Cells(r, 1), .Cells(r, ColsCount)).Value)), ";")
        Call oFile.WriteLine(Line) ' Can I Remove this?...
    Next r
End With

' ...and do the writing to the file here?

Call oFile.Close
Set fso = Nothing
Set oFile = Nothing

3 个答案:

答案 0 :(得分:1)

假设文件的RAM小于2GB,请尝试:

<div class="circle-text large"><div>Small</div></div>

.circle-text{width:50%}
.circle text:after{content:"";display:block;width:100%;height:0;padding-bottom:100%;background:#eb1811;-moz-border-radius:50%;-webkit-border-radius:50%;border-radius:50%}
.circle-text div{float:left;width:100%;padding-top:50%;line-height:1em;margin-top:-.5em;text-align:center;color:#000}
.circle-text.large{width:0%; animation: large 5s ease-in 1;}
@keyframes large {    0%   {width: 0%}    100% {width: 50%}}

答案 1 :(得分:0)

您可以使用vbNewLine分隔符加入所有行,以创建一个大字符串并立即将其全部推出。我不确定在这里使用FileSystemObject有什么好处。这是一个例子

Sub CustomCSV()

    Dim rRow As Range
    Dim lCnt As Long
    Dim aLines() As String
    Dim wf As WorksheetFunction
    Dim sFile As String, lFile As Long

    Set wf = Application.WorksheetFunction
    ReDim aLines(1 To Sheet1.UsedRange.Rows.Count)

    For Each rRow In Sheet1.UsedRange.Rows
        lCnt = lCnt + 1
        aLines(lCnt) = Join(wf.Transpose(wf.Transpose(rRow.Value)), ";")
    Next rRow

    lFile = FreeFile
    sFile = Environ$("TEMP") & Application.PathSeparator & "test.csv"
    Open sFile For Output As lFile
    Print #lFile, Join(aLines, vbNewLine)
    Close lFile

End Sub

答案 2 :(得分:0)

可以一次写入一大块文本。按如下方式调整代码:

Dim completeFile as String
With wb.Sheets(1)
    For r = 1 To RowsCount
        Line = Join(Application.Transpose(Application.Transpose(.range(.Cells(r, 1), .Cells(r, ColsCount)).Value)), ";")
        completeFile = completeFile + Line + vbNewLine
    Next r
End With
Call oFile.write(completeFile)

这样,您就可以将行存储在completeFile中并一次性写入(.write而不是.writeLine)。请注意,这会留下一个vbNewLine太多(最后),您可以删除: completeFile = left(completeFile, len(completeFile) - 1) 如果您的completeFile - 变量此时不为空。