我想让工作表在更改特定单元格时运行宏。
我已经使用下面的代码来初始化确定哪些单元格将导致宏运行的范围,但似乎该范围的生命周期不属于应用程序?
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
可能出现的问题我将不胜感激:
1)正确申报公共变量的地方(例如module1 / this workbook / sheet1?)
2)我认为这是一个坏主意,但是如果我只是在Worksheet_Change()sub中初始化这个范围会不会导致性能过高?
这是发生错误的代码:
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