On error try different password VBA

ExcelHobbit

New Member
Joined
Jan 8, 2020
Messages
23
Office Version
  1. 2010
Platform
  1. Windows
I have a piece of VBA code that opens a workbook that is password encrypted, but could be one of three different passwords:

VBA Code:
Workbooks.Open Filename:="\\Drive1\Folder1\test.xlsx", Password:="Test1"

Workbooks.Open Filename:="\\Drive1\Folder1\test.xlsx", Password:="Test2"

Workbooks.Open Filename:="\\Drive1\Folder1\test.xlsx", Password:="Test3"

if it isn't the first password, i need it to try the second or third password. is there an On error method of doing this?
 

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
Hi,
try following & see if helps you

VBA Code:
Sub OpenWorkbook()
    Dim wb As Workbook
    Dim FileName As String
    Dim Password As Variant
   
    FileName = "\\Drive1\Folder1\test.xlsx"
    
    Application.ScreenUpdating = False
    On Error Resume Next
    For Each Password In Array("Test1", "Test2", "Test3")
        Set wb = Workbooks.Open(FileName, False, False, , Password)
        If Not wb Is Nothing Then Exit For
    Next Password
    On Error GoTo 0
    
    Application.ScreenUpdating = True
    If wb Is Nothing Then MsgBox "Password Not Valid", 64, "Error"
End Sub

Do be mindful that passwords are case sensitive

Dave
 
Upvote 0

Forum statistics

Threads
1,223,893
Messages
6,175,241
Members
452,622
Latest member
Laura_PinksBTHFT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top