公共/全球范围似乎并非始终可用

我想让工作表在特定单元格更改时运行一个macros。

我已经使用下面的代码来初始化确定哪些单元格将导致macros运行的范围,但似乎这个范围的生命周期不是应用程序?

Public ChangeCellList As Range Private Sub Workbook_Open() With Sheets("Program") For i = 7 To .Cells(Rows.Count, "E").End(xlUp).Row If Not IsEmpty(.Cells(i, "E")) Then If ChangeCellList Is Nothing Then Set ChangeCellList = .Range("E" & i) Else Set ChangeCellList = Union(ChangeCellList, .Range("E" & i)) End If End If Next i End With End Sub 

可能的问题我将不胜感激的build议:

1)声明公共variables的正确位置(例如module1 /这个工作簿/ sheet1?)

2)我认为这是一个坏主意,但是如果我刚刚在Worksheet_Change()子类中初始化了这个范围,会不会太糟糕?

这是发生错误的代码:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim Fill As Long Dim StartWeek As Integer Dim Duration As Integer '***Error due to ChangeCellList is nothing*** If Not Application.Intersect(ChangeCellList, Range(Target.Address)) _ Is Nothing Then With Sheets("Program") Fill = Sheets("macroData").Range("C1").Interior.Color StartWeek = InputBox("Please enter the Start Week of this Activity", "Start Week") Duration = InputBox("Please Enter the Duration of this Activity", "Duration") StartCol = StartWeek + 9 For k = 0 To Duration - 1 .Cells(Target.Row, StartCol + k).Value = 1 .Cells(Target.Row, StartCol + k).Interior.Color = Fill .Cells(Target.Row, StartCol + k).Font.Color = Fill Next k End With End If End Sub