Private Sub Worksheet_Change(ByVal Target As Range)
With ActiveSheet
.Unprotect Password:="somepw"
If Range("d17").Value = "Yes" Then
.Range("D22:D78").Locked = False
.Range("D22:D78").Interior.Color = RGB(115, 246, 42)
.Range("Inc_06PCTotRev").Formula = "=SUM($D$22:$D$25)"
ElseIf WorksheetFunction.CountA(Range("d22:D78")) <> 0 Then
If .Range("D22").Locked = True Then
With Range("D22:D78")
.Locked = False
.ClearContents
.Interior.Color = RGB(217, 217, 217)
End With
Else: .Range("D22:D78").ClearContents
End If
Else: .Range("D22:D78").Interior.Color = RGB(217, 217, 217)
.Range("D22:D78").Locked = True
End If
.Protect Password:="somepw"
End With
End Sub
当包含它时,我收到一条错误,指出“对象_worksheet的方法范围失败”并且excel崩溃。如果我发表评论它会毫无问题地解雇。任何帮助将不胜感激。如果这不够具体或没有意义,请告诉我,我会尽力扩展。
答案 0 :(得分:1)
正如我在评论中发布的那样,您处于永无止境的循环中,因为您在工作表更改事件中更改了工作表。您需要跟踪更改呼叫。可以通过创建一个变量来跟踪您调用更改的时间来缓解这种情况,这也是假设名称范围是1个单元格。
Public bRunning As Boolean 'keeps track of when we are making the change
Private Sub Worksheet_Activate()
bRunning = False 'set to false when the sheet is activated
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If bRunning = False Then 'check to see if this is the first change
bRunning = True 'set the variable letting us know we are making the change.
With ActiveSheet
.Unprotect Password:="somepw"
If Range("d17").Value = "Yes" Then
.Range("D22:D78").Locked = False
.Range("D22:D78").Interior.Color = RGB(115, 246, 42)
.Range("Inc_06PCTotRev").Formula = "=SUM($D$22:$D$25)"
ElseIf WorksheetFunction.CountA(Range("d22:D78")) <> 0 Then
If .Range("D22").Locked = True Then
With Range("D22:D78")
.Locked = False
.ClearContents
.Interior.Color = RGB(217, 217, 217)
End With
Else: .Range("D22:D78").ClearContents
End If
Else: .Range("D22:D78").Interior.Color = RGB(217, 217, 217)
.Range("D22:D78").Locked = True
End If
.Protect Password:="somepw"
End With
Else
bRunning = False 'reset the variable as we are done making changes
End If
End Sub
答案 1 :(得分:0)
如果您只需要在调用例程时执行SUM,则可以使用Worksheet.Sum function
:
Application.WorksheetFunction.Sum(Range("$D$22:$D$25"))
如果您确实需要该单元格中的公式,请考虑使用FormulaR1C1 function
:
.Range("Inc_06PCTotRev").FormulaR1C1 = "=SUM(...)"
在Excel下查找FormulaR1C1有助于更好地理解R1C1引用语法。如果要插入公式的单元格为$D$26
,则应替换&#34; ...&#34;以上用&#34; R [-4] C:R [-1] C&#34;如果公式应该在单元格$ E $ 20中,您将替换&#34; ...&#34;以上用&#34; R [2] C [-1]:R [5] C [-1]&#34;。
R [#]引用目标范围/单元格中的行数,C [#]引用目标范围/单元格中的#列。