Home » excel » Permission Denied error in excel vba

Permission Denied error in excel vba

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am writing a function in 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 "

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

##" Debug.Print "Error handling of WriteByteArray" Debug.Print "

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

Answer:

##" 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???

How to&Answers:

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.