Please find my below code where i am getting permission denied error
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
You need to close the file before opening it for a second time.
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
Otherwise your code was correct.
You can use the function below and pass any number of arguments to it.
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
To call it:
Sub T()
Dim path_ As String
path_ = "D:\Test.txt"
WriteToTextFile path_, "One", "Two", "Three", "Four", "Five"
End Sub
Output:
One
Two
Three
Four
Five
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.