VBAでFileSystemObjectを使用してcsvファイルを読み書きすることは可能ですか?
41633 次
2 に答える
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)
CSV
でを作成/開きますFSO
。
その後CSV
、書き込みによって変更できます
これは Excel の例ですが、同じ手法を使用して、Outlook、Access、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
于 2012-02-25T09:31:40.987 に答える
3
可能のようです。
FileSystemObject (FSO) は、Windows ファイル システムにアクセスするための API を提供し、ファイル、ドライブ、テキスト ストリームなどへのアクセスを提供します。FSO は Microsoft Scripting ランタイムに組み込まれ、スタンドアロン アプリケーション (Visual Basic を使用してコーディング) で使用できます。 、たとえば)、VBScript または JScript を使用する Web ページ デザイナー、および Visual Basic for Applications (VBA) を使用する Microsoft Office アプリケーションのユーザー。
いくつかの参照:-
于 2012-02-25T07:44:58.733 に答える