

Excel VBA to open a workbook and switch to a different worksheet.

If the user is incorrect, send them back to a different sheet and display a message.The Excel application is maximized when you open this workbook.įor sake of appearance and/or visablility of crucial data, it is often important that a workbook be maximized. contains VBA to open your real workbook using Workbooks.Open. Yes, instead of performing your checks on workbook open, you could check the username when the sheet is activated. Lastly, none of this will work if someone disables their macros! Comments Example 4: Read and then write content to a text file. Example 3: Open a text file and read its contents using the Open function and file number. It's a good idea to also create a blank sheet to open the workbook onto, to stop details from being read whilst the message box is active. Example 2: Open an Excel workbook in read only' mode and try to write to it. Just want to grab the code and get it working? Here's the complete code: Private Sub Workbook_Open() Dim user As String Dim users( 5) As String users( 0) = "SomeUser" users( 1) = "SomeUser" users( 2) = "SomeUser" users( 3) = "SomeUser" users( 4) = "SomeUser" user = Application.UserName Dim access As Boolean Dim i As Integer access = False For i = 0 To 4 If users(i) = user Then access = True Exit For End If Next If access = False Then MsgBox ( "Sorry, the user """ & "Liam" & """ does not have the correct access rights to view this workbook") ActiveWorkbook.Close End If End Sub NOTEĭont forget to change the number of loops if you change the number of users or some will get missed or an error will occur!
