宏没有完全执行自己

时间:2016-07-05 14:03:03

标签: excel vba excel-vba macros

所以我有以下宏

Private Sub Worksheet_Change(ByVal Target As Range)

BeginRow = 178
EndRow = 178
ChkCol = 8

For RowCnt = BeginRow To EndRow
If IsError(Sheet1.Cells(RowCnt, ChkCol).Value) Then
 Sheet1.Cells(169, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(170, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(171, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(172, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(173, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(174, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(175, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(176, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(177, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(178, ChkCol).EntireRow.Hidden = True
 Sheet1.Cells(179, ChkCol).EntireRow.Hidden = True
End If
Next RowCnt

For RowCnt = BeginRow To EndRow
If Not IsError(Sheet1.Cells(RowCnt, ChkCol).Value) Then
 Sheet1.Cells(169, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(170, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(171, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(172, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(173, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(174, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(175, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(176, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(177, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(178, ChkCol).EntireRow.Hidden = False
 Sheet1.Cells(179, ChkCol).EntireRow.Hidden = False
End If
Next RowCnt
End Sub

你可能做得更漂亮,但我对VBA很新。 公式H178具有以下输入:

`=(H170+H171+H172+H173+H174+H175+H176+H177)/7`

然而,这些单元格H170,H171等从Sheet2获取数据 因此,当H170出错时,H178会给出#REF!这应该自动意味着宏被运行,但它不会,除非我双击单元格H178并按Enter键。

但是如果我想直接在sheet1上更改单元格H170,则为= 5/0(这会产生错误),然后运行宏。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该将此代码放在Worksheet_Calculate事件中,以便在传递错误时重新计算