1

我正在尝试使用 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

第一个错误,我假设我可能会得到另一个错误,是“Permission Denied”。我无法理解这个,因为我是这台机器上的管理员。我查看了目标文件夹,我有填充权限来做我想做的事 - 但是当我查看它的属性时,“只读”框被突出显示 - 为什么会这样?

谢谢

4

1 回答 1

1

您将不被允许写入 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
于 2013-03-12T13:25:09.927 回答