Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA code to check whether file is read-only

Tags:

excel

vba

Please advise as to how to check whether a file is read-only before opening it.

Here is the code I am using to open the file:

myFileNameDir = "H:\Shaikh_Gaus\scratch\VBA\Book16.xlsx"
Workbooks.Open Filename:=myFileNameDir, UpdateLinks:=0

Set ws1 = Worksheets("Students")
like image 902
Gaus Shaikh Avatar asked Dec 06 '25 17:12

Gaus Shaikh


1 Answers

Ways to check or change attributes:

Option Explicit

Sub testFileAttributes()

    Const FILE_NAME As String = "C:\Test.txt"

    If isReadOnly(FILE_NAME) Then MsgBox "File is Read-only"

    If isOpenAsReadOnly Then MsgBox "File is open as Read-only"

    makeReadWrite FILE_NAME

    If Not isReadOnly(FILE_NAME) Then MsgBox "File is not Read-only"

End Sub

.

Public Function isReadOnly(ByVal fName As String) As Boolean

    'vbNormal = 0, vbReadOnly = 1, vbHidden = 2, vbDirectory = 16

    if Len(fName) > 0 Then isReadOnly = GetAttr(fName) And vbReadOnly

End Function

.

Public Function isOpenAsReadOnly(Optional ByRef wb As Workbook = Nothing) As Boolean

    If wb Is Nothing Then Set wb = ActiveWorkbook

    isOpenAsReadOnly = wb.ReadOnly 'opened as read-only within Microsoft Excel

End Function

.


Public Sub makeReadWrite(ByVal fName As String)

    Const READ_ONLY = 1

    Dim fso As Object, fsoFile As Object

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fsoFile = fso.getFile(fName)

    With fsoFile
        If .Attributes And READ_ONLY Then .Attributes = .Attributes Xor READ_ONLY
    End With
End Sub
like image 118
paul bica Avatar answered Dec 08 '25 09:12

paul bica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!