如何在vba中查找excel文件的访问权限(注:2003)

时间:2011-12-02 06:34:22

标签: vba

有人能告诉我如何判断用户是否对excel文件没有访问权限

on error goto label
set a = workbooks.open("some name")
exit sub
label:
    msgbox "Current user does not have access rights or file does not exist or _
             a document with the same name is already opened in another folder"
  end sub

我只是在文件打开错误时使用了一个消息框,我已经给出了3个可能导致错误的原因,但是我希望弹出特定的错误,比如如果用户没有访问权限,则消息应该只包含no访问权限。

我试图捕获错误编号,但所有3个错误都给出了1004编号,因此无法区分。

虽然在谷歌搜索之后,我使用vba.len(vba.dir(filename,vbnormal))=0检查文件是否存在

现在我需要知道用户是否对excel文件具有访问权限。我怎么知道的?非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我认为你基本上有正确的方法。我还将使用错误捕获来确定用户是否有权访问文件。但是,我同意非特定的错误消息不是很有用。

这将显示VBA的特定于错误的消息(即使错误编号保持不变):

MsgBox Err.Description

如果您想要检测错误究竟是什么并使用它,例如要显示您自己的自定义消息,您可以执行以下操作:

If InStr(Err.Description, "could not be found") <> 0 Then
    MsgBox "The file isn't where you said it was."
ElseIf InStr(Err.Description, "access") <> 0 Then
    MsgBox "U can't touch this."
Else
    ' etc.
End If

虽然最好自己检查一下,而不是依靠Err.Description。可以检查文件是否直接存在,例如:

If Dir(filename) = "" Then ' Nicer than vba.len(vba.dir(filename,vbnormal))=0
    MsgBox "The file isn't where you said it was."
End If

我不知道测试用户访问的等效功能,所以我会回过头来看Err.Description的内容。