请在下面的代码中找到我获得许可拒绝错误
Sub VBA()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
i = "info"
Set ts = fso.CreateTextFile("z:\" & i & ".txt", True)
File = "z:\" & i & ".txt"
n = FreeFile()
Open File For Output As #n '''HERE I AM GETTING ERROR
Print #n, s
End Sub
答案 0 :(得分:1)
您需要先关闭文件,然后再打开它。
Sub VBA()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
i = "info"
Set ts = fso.CreateTextFile("z:\" & i & ".txt", True)
ts.Close ' this is what you were missing, the file needs to be closed
File = "z:\" & i & ".txt"
n = FreeFile()
Open File For Output As #n
Print #n, s
End Sub
否则,您的代码是正确的。
答案 1 :(得分:0)
您可以使用下面的函数并将任意数量的参数传递给它。
Public Sub WriteToTextFile(ByVal Filename As String, ParamArray args() As Variant)
On Error GoTo ErrProc
Dim hFileDest As Integer
hFileDest = FreeFile
Open Filename For Append As #hFileDest
Dim idx As Integer
For idx = LBound(args) To UBound(args)
Print #hFileDest, args(idx)
Next idx
Leave:
On Error Resume Next
Close #hFileDest
On Error GoTo 0
Exit Sub
ErrProc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
要打电话:
Sub T()
Dim path_ As String
path_ = "D:\Test.txt"
WriteToTextFile path_, "One", "Two", "Three", "Four", "Five"
End Sub
输出:
One
Two
Three
Four
Five