间歇性错误:对象不支持此属性或方法

我有一个多张工作簿。 在sheet3中,我有一个button(名为button1),用于运行下面的代码,在使用button1时运行良好:

Private Sub CommandButton1_Click() Call PivotColor(Sheet3, "1Up", "1Down", 30, 6) End Sub 

在这里,他的代码function“PivotColor”:

 Sub PivotColor(Sheetname As Worksheet, UpArrow As String, DownArrrow As String, Columnreference As Integer, Rowreference As Integer) If (Sheetname.Cells(Rowreference, Columnreference) >= 0) Then ' Select RED Arrow Sheetname.Shapes.Range(Array(DownArrrow)).Select ' Hide the Red Arrow With Selection.ShapeRange.Fill .Visible = msoTrue .Transparency = 1 .Solid End With ' Otherwise it means the value of the cells is negative... Else ' Select RED Arrow Sheetname.Shapes.Range(Array(DownArrrow)).Select ' Display the Red Arrow With Selection.ShapeRange.Fill .Visible = msoTrue .Transparency = 0 .Solid End With End If End Sub 

现在,如果我在第二个工作表(名为sheet2)中创build一个新button(名为button2)并将相同的代码关联到该工具,则会出现“对象不支持此属性或方法”的错误。

 Private Sub CommandButton2_Click() Call PivotColor(Sheet3, "1Up", "1Down", 30, 6) End Sub 

如果我点击“debugging”,则突出显示这一行:

 With Selection.ShapeRange.Fill 

所以基本上,这里的想法是执行应该发生在sheet3上的一个进程,但是从sheet2启动它。

我不明白什么是不工作…任何想法?

您使用。 SelectionSelection可能会产生混淆。 当您单击Sheet3上的button时,您在Sheet3(ActiveSheet)上。 单击Sheet2上的button时不是这样。 尝试编码而不使用。select。

 Sub PivotColor(Sheetname As Worksheet, UpArrow As String, DownArrrow As String, Columnreference As Integer, Rowreference As Integer) With Sheetname ' Show/Hide the Red Arrow With .Shapes(DownArrrow).ShapeRange.Fill .Visible = msoTrue .Transparency = Abs(.Cells(Rowreference, Columnreference) >= 0) .Solid End With End With End Sub 

单个形状不需要整个.Shapes.Range(Array(...))代码。 我通过将布尔结果直接计入.Transparency属性= s值来收紧代码。

对我来说你的代码看起来不错。

我会尝试下面的代码,而不是你的线,虽然我wouldn;吨期待这个有所作为。

'select红色箭头'隐藏红色箭头

 With Sheetname.Shapes.Range(Array(DownArrrow)).ShapeRange.Fill .Visible = msoTrue .Transparency = 1 .Solid End With 

此外,在Sheet2中有一个variables声明在模块级别称为“Sheet3”如果是这样抓住这个,而不是使用“sheet3”工作表对象。 – 只是一个想法。