2012-02-25 106 views

回答

10

這當然是。

基本語法如

Set objFSO = CreateObject("scripting.filesystemobject") 
    'create a csv file 
    Set objTF = objFSO.createtextfile("C:\test\myfile.csv", True, False) 
    'open an existing csv file with writing ability 
    Set objTF = objFSO.OpenTextFile("C:\test\myfile.csv", 8) 

將創建/打開一個CSVFSO

CSV然後可以通過寫它

雖然這是一個Excel的例子,你可以使用相同的技術來存儲從Outlook,訪問時,Word等

Const sFilePath = "C:\test\myfile.csv" 
Const strDelim = "," 
Sub CreateCSV_FSO() 
    Dim objFSO 
    Dim objTF 
    Dim ws As Worksheet 
    Dim lRow As Long 
    Dim lCol As Long 
    Dim strTmp As String 
    Dim lFnum As Long 

    Set objFSO = CreateObject("scripting.filesystemobject") 
    Set objTF = objFSO.createtextfile(sFilePath, True, False) 

    For Each ws In ActiveWorkbook.Worksheets 
     'test that sheet has been used 
     Set rng1 = ws.UsedRange 
     If Not rng1 Is Nothing Then 
      'only multi-cell ranges can be written to a 2D array 
      If rng1.Cells.Count > 1 Then 
       X = ws.UsedRange.Value2 
       'The code TRANSPOSES COLUMNS AND ROWS by writing strings column by column 
       For lCol = 1 To UBound(X, 2) 
        'write initial value outside the loop 
        strTmp = IIf(InStr(X(1, lCol), strDelim) > 0, """" & X(1, lCol) & """", X(1, lCol)) 
        For lRow = 2 To UBound(X, 1) 
         'concatenate long string & (short string with short string) 
         strTmp = strTmp & (strDelim & IIf(InStr(X(lRow, lCol), strDelim) > 0, """" & X(lRow, lCol) & """", X(lRow, lCol))) 
        Next lRow 
        'write each line to CSV 
        objTF.writeline strTmp 
       Next lCol 
      Else 
       objTF.writeline IIf(InStr(ws.UsedRange.Value, strDelim) > 0, """" & ws.UsedRange.Value & """", ws.UsedRange.Value) 
      End If 
     End If 
    Next ws 

    objTF.Close 
    Set objFSO = Nothing 
    MsgBox "Done!", vbOKOnly 

End Sub 
+0

'設置objTF =記錄被修改objFSO.OpenTextFile(「C:\ test \ myfile.csv」,8)'該行總是出現** 70 - Permission Denied **錯誤,無論我選擇哪個文件夾。它在我刪除該行後運作。 – chiliNUT 2014-09-17 18:09:50

+0

當您運行代碼時,您是否已經打開了csv? – brettdj 2014-09-17 22:08:32

+0

不,這是當我第一次嘗試創建它時 – chiliNUT 2014-09-17 22:09:13

3

看起來可能。

FileSystemObject(FSO)提供一個API來訪問Windows文件系統,提供對文件,驅動器,文本流等的訪問。FSO嵌入在Microsoft Scripting運行時中,可獨立使用應用程序(例如使用Visual Basic編碼),使用VBScript或JScript的網頁設計人員以及使用Visual Basic for Applications(VBA)的Microsoft Office應用程序的用戶。

一些參考: -

Using The FileSystemObject With VB and VBA

How do I use FileSystemObject in VBA?