2017-02-16 69 views
0

我試圖使用Freefile導出到文本文件。該過程正在製作一個包含許多列的工作表,並將每個列作爲文本導出。VBA多個FreeFile導出爲CSV

我一直在得到的問題是錯誤55代碼「文件已打開」。

因爲我希望列範圍作爲輸入變量的長度,我不知道我需要多少自由文件命令。

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的,因爲我需要根據來源的未知列數.... ....

+0

您不關閉內循環中的文件,所以它永遠不會被更改。 –

回答

1

FreeFile每次調用它時都會生成一個新的文件編號。

但是在你的代碼中,你正在爲每一行調用它。

而你錯誤處理是不恰當的,所以我添加了一個子,以顯示你應該如何使用! ;)

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 
+0

哇,謝謝大.....是我錯了簡歷聲明的主要內容?或者「iF1 = FreeFile」必須再循環一次。 –

+0

@The_BMan:'FreeFile'和'Open ...'都需要在循環之外,至於錯誤處理,它只是它在你的代碼中間(如果它被處理正確),但即使沒有任何錯誤,每列的每行也會觸發你的! ;) – R3uK