1

我正在用 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 中收到权限被拒绝错误。Kill 和 Open 有人可以帮助我吗?

4

1 回答 1

3

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

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

于 2013-06-10T11:22:41.960 回答