• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

VBA code which is in the last runs in the beginning and then the first macro runs ?

Marsdon

New Member
Hi,

I want to know why does a VBA code written in the last starts running in the beginning and then the First one starts running ?

For eg: I have given the code
Code:
Private Sub Worksheet_Calculate()

ActiveSheet.Unprotect Password:="454984djnfui184"

Dim LastRow As Long, c As Range
Application.EnableEvents = False
LastRow = Cells(Cells.Rows.Count, "G").End(xlUp).Row
On Error Resume Next
For Each c In Range("G9:G" & LastRow)
If c.Value = 1 Then
c.EntireRow.Hidden = True
ElseIf c.Value = 0 Then
c.EntireRow.Hidden = False
End If
Next
On Error GoTo 0
Application.EnableEvents = True

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Worksheets("Region Broker ID Report").Range("A:Z").Locked = True
ActiveSheet.Protect AllowUsingPivotTables:=True, Password:="454984djnfui184"

MsgBox "Completed successfully."

End Sub
 
Last edited by a moderator:
Hi Marsdon ,

I am not sure I have understood your question ; the two macros you have posted viz.

Worksheet_Calculate

Worksheet_SelectionChange

are what are known as event procedures ; these are procedures which are not run by the user ; they are executed by Excel , as and when the associated events are triggered.

Thus , the Worksheet_SelectionChange event procedure is triggered when ever you move the cursor in the concerned worksheet , either by using the mouse or by using the cursor movement keys.

Since these are worksheet level procedures , they will be triggered only when action takes place in the sheet where they are placed ; thus , if they are placed in the section associated with Sheet2 , if you activate Sheet3 and move the cursor or force a worksheet level recalculation by data entry in any cell , these two procedures will not be executed.

Even on the worksheet where these two procedures are placed , it is not necessary that the second procedure will always be executed before the first or the other way around.

When the cursor is moved into a cell , thus changing the activecell selection , the second procedure is triggered ; but now , if you enter any data in the activecell which might force a worksheet recalculation , the first procedure will be triggered.

Hence , the execution of the two procedures is in no way related to where they are physically located in relation to each other.

This is true also of all other procedures ; you can have a procedure written at the top , being called by a procedure which is physically placed below it.

Narayan
 
Back
Top