我得到
运行时错误 91:未设置对象变量或块变量
当我从云存储位置打开我的程序时,它以警告问题"启用内容"打开。 当我单击启用时,出现错误 91。 如果我从电脑打开,没有问题。 我确实需要能够从云存储位置下载和打开。我的代码如下。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = True
With ActiveSheet
.Cells.Interior.ColorIndex = xlNone
If Target.Rows.Count = 1 Then
Range("A" & Target.Row, "J" & Target.Row).Interior.ColorIndex = 27
End If
End With
End Sub
将With ActiveSheet
更改为With Me
,并为Range
指定Me
,如Me.Range
(或使其使用 with 语句并以点开头,如.Range
(。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = True
With Me
.Cells.Interior.ColorIndex = xlNone
If Target.Rows.Count = 1 Then
.Range("A" & Target.Row, "J" & Target.Row).Interior.ColorIndex = 27
End If
End With
End Sub
为什么这是一个重要的区别?
ActiveSheet
是在代码运行时具有焦点(位于顶部(的工作表。但这不一定是触发事件或Target
所在的工作表。因此,您尝试更改不同工作表的颜色。不惜一切代价避免使用ActiveSheet
。在大多数情况下,它不是必需的(除非在极少数情况下,例如,如果您编写插件或类似的东西(。
您可能会从阅读中受益 如何避免使用在Excel VBA中选择,这是一个非常相似的主题。