vba excel vba中的权限被拒绝错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17022591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:33:49  来源:igfitidea点击:

Permission Denied error in excel vba

vbaexcel-vbaexcel

提问by Shabeer Thalaprathu

I am writing a function in excel vba

我正在用 excel vba 写一个函数

 Function WriteByteArray(vData As Variant, sFileName As String, Optional bAppendToFile As Boolean = False) As Boolean
    Dim iFileNum As Integer, lWritePos As Long

    Debug.Print " --> Entering WriteByteArray function with " & sFileName & " file to write."
    On Error GoTo ErrFailed
    If bAppendToFile = False Then
        If Len(Dir$(sFileName)) > 0 And Len(sFileName) > 0 Then
            'Delete the existing file
            VBA.Kill sFileName
        End If
    End If

    iFileNum = FreeFile
    Debug.Print "iFileNum = " & iFileNum
    'Open sFileName For Binary Access Write As #iFileNum
    Open sFileName For Binary Lock Read Write As #iFileNum

    If bAppendToFile = False Then
        'Write to first byte
        lWritePos = 1
    Else
        'Write to last byte + 1
        lWritePos = LOF(iFileNum) + 1
    End If

    Dim buffer() As Byte
    buffer = vData
    Put #iFileNum, lWritePos, buffer

    WriteByteArray = True
    Exit Function
ErrFailed:
        Debug.Print "################################"
        Debug.Print "Error handling of WriteByteArray"
        Debug.Print "################################"
        FileWriteBinary = False
        Close iFileNum
        Debug.Print Err.Description & "(" & Err.Number & ")"
    End Function

I am getting a permission denied error in VBA.Kill and Open Can any one help me???

我在 VBA.Kill 和 Open 中收到一个权限被拒绝错误,有人可以帮我吗???

回答by Alex K.

You are forgetting to close the file when the function returns, you currently only do so when there is an error.

您忘记在函数返回时关闭文件,您目前仅在出现错误时才这样做。

The file handle persists between runs of you code so when you re-run it you attempt to operate on a file that is already open and explicitly locked, causing an error.

文件句柄在您的代码运行之间持续存在,因此当您重新运行它时,您尝试对已经打开并明确锁定的文件进行操作,从而导致错误。