簡體   English   中英

VBA 打開輸出權限被拒絕

[英]VBA open for output permission denied

請在下面的代碼中找到我收到權限被拒絕錯誤的地方

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

您需要先關閉文件,然后再打開它。

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

否則你的代碼是正確的。

您可以使用下面的函數並將任意數量的參數傳遞給它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM