When working with workbooks using VBA, there may be times when you want to retrieve information from another workbook.
By opening the other workbook as read-only, you can prevent accidental changes to the data while displaying and retrieving the necessary information.
This page introduces how to open a workbook as read-only using VBA.
Open Workbook as Read-Only
To open a workbook as read-only, specify True for the ReadOnly argument of the Workbooks.Open method.
Workbooks.Open(FileName, ReadOnly:=True)
Specify the full path of the file in FileName. All arguments other than FileName are optional.
The following code is an example of opening sample.xlsx in the user’s Documents folder as read-only.
Dim wb As Workbook, path As String
' User's Documents folder
path = Environ("USERPROFILE") & "\Documents\sample.xlsx"
' Open the workbook as read-only
Set wb = Workbooks.Open(path, ReadOnly:=True)
' Close the workbook (no save prompt is needed for a read-only workbook)
wb.Close SaveChanges:=False
Notes
A workbook opened as read-only cannot be saved over the original file with the Save method (a runtime error occurs). To keep your changes, use the SaveAs method to save it under a different name.
You can check whether an opened workbook is read-only with the wb.ReadOnly property (True means read-only).
If the path is incorrect or you do not have access permissions, the workbook will not open. It is recommended to implement proper error handling.
The following code is an example of closing the workbook if it was already opened when an error occurs.
Public Sub OpenReadOnlyWorkbook()
On Error GoTo ErrorHandler
Dim wb As Workbook, path As String, errMsg As String
' User's Documents folder
path = Environ("USERPROFILE") & "\Documents\sample.xlsx"
' Open the workbook as read-only
Set wb = Workbooks.Open(path, ReadOnly:=True)
' Some processing
' Close the workbook
wb.Close SaveChanges:=False
Exit Sub
ErrorHandler:
' Save the message first because On Error statements clear Err
errMsg = Err.Description
' If the workbook was open when the error occurred, close it
If Not wb Is Nothing Then
On Error Resume Next
wb.Close SaveChanges:=False
On Error GoTo 0
End If
MsgBox "An error occurred: " & errMsg
End Sub
Summary
We introduced how to open an Excel workbook as read-only using VBA.
Please refer to the sample code above and customize it according to your needs.