0

I'm running a macro in one workbook which is constantly running. When I open another workbook the macro breaks and its falls out of range. How can I lock the macro on that particular sheet? macro code is:

Sub startTimer()
On Error Resume Next
ActiveSheet.Unprotect Password:="***"
Application.OnTime Now + TimeValue("00:00:01"), "Increment_count", Schedule:=False
Application.OnTime Now + TimeValue("00:00:01"), "Increment_count"

End Sub

Sub Increment_count()
If ActiveCell.Column = 9 Then
    ActiveCell.Value = ActiveCell + 1
    startTimer
Else
    MsgBox "Timer works only in I column", vbCritical, "Error"
    End If
End Sub

Sub stopTimer()
On Error Resume Next
Application.OnTime Now + TimeValue("00:00:01"), "Increment_count", Schedule:=False
ActiveSheet.Protect Password:="***"
ActiveWorkbook.Save
End Sub
Justinas
  • 1
  • 1

1 Answers1

1

This answer is an extension of the comment by Shai Rado

Activeworkbook and Activesheet reference to the sheet currently focussed on. A better way is to name your worksheet of interest and get that worksheet by its name.

Dim correctSheet as Worksheet
correctSheet = Worksheets("SheetName")
correctSheet.Unprotect ' etc..

Look also to this question:Declaring variable workbook / Worksheet vba

This reference might also be useful http://www.excel-easy.com/vba/workbook-worksheet-object.html

Community
  • 1
  • 1
pvl
  • 194
  • 1
  • 10