Excel 3/3
12 Jan 2022WorkbookEvents and WorksheetEvents
SheetActivate
used for triggering something once the worksheet is activated.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox ("Hey you just selected " & ActiveSheet.Name)
End Sub
BeforePrint
Used to perform some action whenever the print button is clicked.
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim PrtResponse As Integer
PrtResponse = MsgBox("This is a warning message before printing!", vbOKCancel, "Everything alright?")
If PrtResponse = vbCancel Then Cancel = True
End Sub
SheetChange
Used to perform some action whenever there is any modification in the sheet.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
'Display message box stating which sheet was just activated
MsgBox ("You just selected " & ActiveSheet.Name)
End Sub
SaveCopyAs
Used to save a copy of the current workbook
ThisWorkbook.SaveCopyAs Filename:=</folder_path/save_filename>
Workbook BeforeClose
Used to do perform some task or display something before the Workbook closes
If you have a user form, and want to show it:
<userform_name>.Show
Hide a sheet:
<shee_name>.Visible = xlSheetVeryHidden
To run a module function that you have created from another code block of a different entity (Example: Code window of an UserForm)
Run "<Module_Function_name>"
Example:
Private Sub UserForm_Initialize()
Run "UserLog"
End Sub
Get number of worksheet, and select a random worksheet:
x = Worksheets.Count
Sheets(Application.WorksheetFunction.RandBetween(1, x)).Select
To check whether two group of cells intersect:
'This code goes in the "ThisWorksheet" Object
Private Sub Worksheet_Change(ByVal Target As Range)
'Original code from the MS Website:
'https://msdn.microsoft.com/en-us/library/office/ff835030.aspx
'Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
'If isect Is Nothing Then
' MsgBox "Ranges do not intersect"
'Else
' isect.Select
'End If
'Iteration 1
'Set isect = Application.Intersect(Target, Range(Range("A3"), Range("A3").End(xlDown)))
'If isect Is Nothing Then
' MsgBox "Ranges do not intersect"
'Else
' MsgBox "Ranges DO intersect"
'End If
'Iteration 2
Set isect = Application.Intersect(Target, Range(Range("A3"), Range("A3").End(xlDown)))
If isect Is Nothing Then
End
Else
MsgBox "Hey, don't change this to " & Target.Value
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
End If
End Sub
To protect a sheet with a password:
Private Sub Worksheet_Activate()
Dim UserPassWord As String
'Take the user somewhere else
ShGuide.Select
'Input box to get password
UserPassWord = InputBox("This sheet is highly classified." & vbNewLine & _
"You must be very important to view the contents." & vbNewLine & _
"Please enter password below", "Top Secret!")
'Logical test to see if the password was correct
If UserPassWord = "Password" Then
'Turn OFF the "Events" to enable selection without triggering the code again!
Application.EnableEvents = False
'Select the top secret sheet
ShTopSecret.Select
'Ensure "Events are turned back on
Application.EnableEvents = True
Else
'Display message box if password was incorrect
MsgBox "You'd better RUN. Security have been notified!", vbCritical, "Access Denied!"
End
End If
End Sub
User-defined Functions
Example1:
'User Defined Functions (UDF's) always begin with the word "Function"
Function Pie_multiple(MyValue As Variant)
Pie_multiple = MyValue * 3.14159
End Function
Example2:
Function Square(MyValue As Variant)
Square = MyValue * MyValue
End Function
Example3:
Function WhereIsThisFile_residing()
WhereIsThisFile_residing = ThisWorkbook.Path
End Function
Example4: Countdown Timer
Function BDayCountdown(MyValue As Variant)
'Set up the variable
Dim CountDay As Variant
Dim CountHour As Variant
Dim CountMinute As Variant
Dim CountSecond As Variant
'Forces a recalc on F9 (or Calc now)
Application.Volatile
'Calculate the individual elements
CountDay = Int(MyValue - Now()) & " days, "
CountHour = Hour(MyValue - Now()) & " hours, "
CountMinute = Minute(MyValue - Now()) & " minutes, "
CountSecond = Second(MyValue - Now()) & " seconds!"
'Build the string and assign it to "BDayCountDown"
BDayCountdown = CountDay & CountHour & CountMinute & CountSecond
'Alternative method
'BDayCountdown = Int(MyValue - Now()) & " days, " & _
Hour(MyValue - Now()) & " hours, " & _
Minute(MyValue - Now()) & " minutes, and " & _
Second(MyValue - Now()) & " seconds!"
End Function
To call a user-defined function from a different Workbook:
='<Workbook_name_where_the function_resides.xlsm>'!<function_name>(<parameter>)
='User_defined_function.xlsm'!Pie_multiple(10)
To create a folder:
MkDir "<folder_path>\<folder_name>"
To send email using Outlook:
Private Sub SimpleSendMailOriginalCode()
'This is the original code, which is slightly modified above
'This code uses "Late Binding". This means the code
'can be used from any PC.
Dim OutlookApp As Object 'Declare Outlook as an object
Dim OutgoingEmail As Object 'Declare the email as an object
Dim MyBodyText As String 'Holds the message itself
'Create an object for Outlook
Set OutlookApp = CreateObject("Outlook.Application")
'Create an object for the email
Set OutgoingEmail = OutlookApp.CreateItem(0)
'Build the text for the body of the message (could be read from ranges in Excel)
MyBodyText = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
'Turns off error handling (stops the "someone is trying to send an email" message)
On Error Resume Next
With OutgoingEmail
.To = "someone@somewhere.com"
'.CC = ""
'.BCC = ""
.Subject = "This is the Subject line"
.Body = MyBodyText
'.Attachments.Add ("C:Users\Alan\Desktop\Book1.xlsx")
.Send
End With
'Cancels the error trap above
On Error GoTo 0
'Destroy object variables
' (in the reverse order in which we declared them)
Set OutgoingEmail = Nothing
Set OutlookApp = Nothing
End Sub