VBA将多个FreeFile导出为CSV

我试图使用Freefile导出到文本文件。 这个过程是带有许多列的工作表,并为每个列导出它作为文本。

我一直在得到的问题是错误55代码“文件已经打开”。

因为我想列的范围作为input变长,我不知道多less自由文件命令我需要。

For j = intColumOffsett + 1 To intLastColumn strDate = wkSource.Cells(1, j).Value strNewFile = strDirectory & strDate & " New.csv" For i = 1 To intLastRow strTarget = strTarget & wkSource.Cells(i, 1).Value & "," strTarget = strTarget & wkSource.Cells(i, 2).Value & "," strTarget = strTarget & wkSource.Cells(i, 3).Value & "," strTarget = strTarget & strDate & "," strTarget = strTarget & wkSource.Cells(i, j).Value ' It's this this section I'm not sure about \/ 'Set strNewFile = Nothing 'Stop iF1 = FreeFile(j) 'Close #iF1 On Error GoTo Error: Open strNewFile For Output As #iF1 Print #iF1, strTarget Debug.Print strTarget strTarget = "" Error: MsgBox (Err.Description) Next i Close #iF1 Next j 

我怎样才能避免这些错误将导出尽可能多的新的CSV的,因为我需要根据来源的列数未知…. ?????

FreeFile每次调用时都会生成一个新的文件编号。

但是在你的代码中,你要为每一行调用它。

而你error handling是不恰当的,所以我加了一个子,以显示你应该如何使用! ;)

  Sub MultiFreeFiles() '''... For j = intColumOffsett + 1 To intLastColumn strDate = wkSource.Cells(1, j).Value strNewFile = strDirectory & strDate & " New.csv" iF1 = FreeFile On Error GoTo Error: Open strNewFile For Output As #iF1 For i = 1 To intLastRow strTarget = vbNullString With wkSource strTarget = strTarget & .Cells(i, 1).Value & "," strTarget = strTarget & .Cells(i, 2).Value & "," strTarget = strTarget & .Cells(i, 3).Value & "," strTarget = strTarget & strDate & "," strTarget = strTarget & .Cells(i, j).Value End With 'wkSource Debug.Print strTarget Print #iF1, strTarget Next i Close #iF1 Next j '''... Exit Sub Error: MsgBox (Err.Description) Resume End Sub