Check Folder Permissions Before Save VBA

后端 未结 2 1904
梦谈多话
梦谈多话 2021-01-23 02:16

I Have created a user form that will open an excel file open & hide the excel. When closing the user form will save & close the excel file. However, there are two types

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 02:21

    The answer above from Macro Man, while succinct and useful, will not work in an environment where folder access is managed by user groups instead of user names. As many corporate environments - including my own - use this method to manage folder access, I have posted below a solution that will assess a user's actual permissions to a folder. This will work whether the user has been granted individual or group access to a folder.

    Private Function TestWriteAccess(ByVal StrPath As String) As Boolean
    
    Dim StrName As String, iFile As Integer, iCount As Integer, BExists As Boolean
    
    'Set the initial output to False
    TestWriteAccess = False
    
    'Ensure the file path has a trailing slash
    If Right(StrPath, 1) <> "\" Then StrPath = StrPath & "\"
    
    'Ensure the path exists and is a folder
    On Error Resume Next
    BExists = (GetAttr(StrPath) And vbDirectory) = vbDirectory
    If Not BExists Then GoTo Exit_TestWriteAccess 'Folder does not exist
    'Set error handling - return False if we encounter an error (folder does not exist or file cannot be created)
    On Error GoTo Exit_TestWriteAccess
    
    'Get the first available file name
    Do
        StrName = StrPath & "TestWriteAccess" & iCount & ".tmp"
        iCount = iCount + 1
    Loop Until Dir(StrName) = vbNullString
    
    'Attempt to create a test file
    iFile = FreeFile()
    
    Open StrName For Output As #iFile
    Write #iFile, "Testing folder access"
    Close #iFile
    
    TestWriteAccess = True
    
    'Delete our test file
    Kill StrName
    
    Exit_TestWriteAccess:
    End Function
    

    In researching file access, I also stumbled upon Check Access Rights to File/Directory on NTFS Volume by Segey Merzlikin on FreeVBcode.com; this solution is overkill for my needs (and OP's) but will return the exact access rights that a user has to a particular file.

提交回复
热议问题