gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:07:45 27 4
gpt4 key购买 nike

我正在用 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 有人可以帮助我吗?

最佳答案

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

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

关于vba - excel vba中的权限被拒绝错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022591/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com