excel vba中的权限被拒绝错误

时间:2013-06-10 11:14:22

标签: vba excel-vba excel

我正在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

我在VBA中获得了权限被拒绝错误。杀死和打开任何人都可以帮助我???

1 个答案:

答案 0 :(得分:3)

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

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