无法写入VBA中的文本文件

时间:2013-03-12 13:20:27

标签: vba ms-access

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

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

由于

1 个答案:

答案 0 :(得分:1)

您将不被允许写入C root,因此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