无法写入VBA中的文本文件
问题描述:
我试图使用VBA写入文本文件。这是我的代码:无法写入VBA中的文本文件
DoCmd.SetWarnings False
'Delete all data from the source table
DoCmd.RunSQL "DELETE * FROM tblSource;"
'Run query to fill it
DoCmd.OpenQuery "qryFilltblSource"
' Declare a FileSystemObject.
Dim fso As FileSystemObject
' Create a FileSystemObject.
Set fso = New FileSystemObject
' Declare a TextStream.
Dim stream As TextStream
' Create a TextStream. The true part overwrites a text file it it already exists
Set stream = fso.CreateTextFile("C:\Target Folder", True)
Set rst = CurrentDb.OpenRecordset("tblSource")
Dim i As Integer
i = 1
Do Until rst.EOF = True
stream.WriteLine (rst!i)
i = i + 1
rst.MoveNext
Loop
stream.Close
DoCmd.SetWarnings True
第一个错误,我假设我可能会得到另一个,是“权限被拒绝”。我无法理解这个,因为我是这台机器上的管理员。我查看了目标文件夹,并且已经有权限执行我想要的操作 - 但是,当我查看其属性时,“只读”框突出显示 - 这是为什么?
感谢
答
你将不会被允许写入到C盘根,所以C:\Target Folder\Atextfile.txt
考虑使用TransferText:
DoCmd.TransferText acExportDelim, , tblSource, "c:\docs\output.txt", True
请注意,你不能说:
Dim i As Integer
i = 1
Do Until rst.EOF = True
stream.WriteLine (rst!i) <-- i is a record, not a field
i = i + 1
rst.MoveNext
Loop
您需要
Do Until rst.EOF
For i=0 to rst.Fields.Count-1
stream.WriteLine rst(i) ''or rst(i) & "" to avoid problems with Null
Next
rst.MoveNext
Loop
切勿使用设置警告,它会转身咬你:http://stackoverflow.com/questions/11213892/whats-the-difference-between-docmd-setwarnings-and-currentdb-execute/11213943# 11213943 – Fionnuala 2013-03-12 13:52:03