Button.Visible = False在VBA中不起作用

我有一个macros启用工作簿,并在过去它一直工作正常,但自从我有一个Windows更新macros导致工作簿崩溃,给我一个错误“运行时错误'424':所需的对象“。 我似乎无法弄清楚为什么我的代码不再工作。 这是我的代码。

Private Sub Worksheet_Change(ByVal Target As Range) 'Rage Button If Cells(1, 12).Value = "Barbarian" Then 'CHANGE THE CELL TO THE ADRESS OF THE TRIGGER CELL Rage.Visible = True 'CHANGE TO THE NAME OF THE BUTTON Else Rage.Visible = False 'CHANGE TO THE NAME OF THE BUTTON End If 'Raging Brutality If Cells(1, 12).Value = "Barbarian" Then If WorksheetFunction.CountIf(Range(Cells(40, 1), Cells(61, 1)), "Raging Brutality") Then Brutality.Visible = True Else Brutality.Visible = False End If Else Brutality.Visible = False End If 'Sneak Button If Cells(1, 12).Value = "Rogue" Then 'CHANGE THE CELL TO THE ADRESS OF THE TRIGGER CELL Sneak.Visible = True 'CHANGE TO THE NAME OF THE BUTTON Else Sneak.Visible = False 'CHANGE TO THE NAME OF THE BUTTON Cells(25, 7).Value = 0 End If End Sub 

不是你的特定问题的答案,但由于Visible是一个布尔属性,你的代码可以减less:

 Private Sub Worksheet_Change(ByVal Target As Range) Rage.Visible = (Cells(1, 12).Value = "Barbarian") Brutality.Visible = (Cells(1, 12).Value = "Barbarian" And _ WorksheetFunction.CountIf( _ Cells(40, 1).Resize(22,1), "Raging Brutality") > 0) Sneak.Visible = (Cells(1, 12).Value = "Rogue") If Not Sneak.Visible Then Cells(25, 7).Value = 0 End Sub 

你要么开始定义你的对象

 Rage = ActiveSheet.Shapes("Rage") 

或以他们接受的格式引用他们,例如

 ActiveSheet.Shapes("Rage").Visible = False 


使用Tim Williams的 snipplet你的代码将如下所示:

 Private Sub Worksheet_Change(ByVal Target As Range) ActiveSheet.Shapes("Rage").Visible = (Cells(1, 12).Value = "Barbarian") ActiveSheet.Shapes("Brutality").Visible = (Cells(1, 12).Value = "Barbarian" And _ WorksheetFunction.CountIf( _ Cells(40, 1).Resize(22,1), "Raging Brutality") > 0) ActiveSheet.Shapes("Sneak").Visible = (Cells(1, 12).Value = "Rogue") If Not ActiveSheet.Shapes("Sneak").Visible Then Cells(25, 7).Value = 0 End Sub 

确保您的对象被选中后,通过选中名称框命名为愤怒残酷潜行

更新:我做了一个更清晰简洁的子。
似乎你不能重命名button,只是看看他们的名字,并用Ctrl + Hreplace每个名字(愤怒,残酷,潜行)。

 Private Sub Worksheet_Change(ByVal Target As Range) ActiveSheet.Shapes("Rage").Visible = False 'let's make all invisible before evaluation ActiveSheet.Shapes("Brutality").Visible = False ActiveSheet.Shapes("Sneak").Visible = False Select Case Cells(1, 12).Value Case "Barbarian" ActiveSheet.Shapes("Rage").Visible = True If WorksheetFunction.CountIf(Range(Cells(40, 1), Cells(61, 1)), "Raging Brutality") Then ActiveSheet.Shapes("Brutality").Visible = True End If Case "Rogue" ActiveSheet.Shapes("Sneak").Visible = True Case Else Cells(25, 7).Value = 0 End Select End Sub