当没有指令时,宏正在清除其他工作表中的单元格

时间:2015-10-17 06:54:22

标签: excel vba excel-vba

我收到以下错误。

我在模块1中有两个宏,在模块4中有另外两个宏分别命名为“RestricPref”和“TailoredInputs”。现在“TailoredInputs”应该在“输入”表单中进行更改,我只使用With命令来执行此操作,但由于未知原因,它也在“首选项”表单中进行更改。

要更好地理解问题,请首先运行模块1,然后在“PreferencesTab”中查看更改,然后运行模块4,您会发现它在“PreferencesTab”中更改了数据,而不应该这样做。

有人能找到这个bug吗?

运行良好的Module1代码:

Option Explicit
Sub RestrictPref()    
Dim ws As Worksheet

Set ws = Sheets("Preferences")

With ws
'Set to No
Range("C11").Value = "No"
Range("C13").Value = "No"
Range("F11:H11").Value = "No"
Range("F13:H13").Value = "No"
Range("C17:E17").Value = "No"
Range("C19:E19").Value = "No"
Range("C23:H23").Value = "No"
Range("D27:H27").Value = "No"
Range("C31:F31").Value = "No"

'Clear Contents
Range("D11:e11").ClearContents
Range("D13:e13").ClearContents

'Set C27 to Yes
Range("C27").Value = "Yes"

End With
End Sub

模块4代码生成错误:

Option Explicit
Sub TailoredInputs()
    Dim ws As Worksheet
    Dim i, j, l As Integer, rngHide As Range

    Set ws = Sheets("Inputs")
    Application.ScreenUpdating = False
    With ws
    ws.Range("A7:A200").EntireRow.Hidden = False

    For j = 10 To 152
        If ws.Cells(j, "J").Value = "H" Or ws.Cells(j, "K").Value = "H" Then
            For l = 4 To 9
                If ws.Cells(j, l).Interior.ColorIndex = 19 Then
                      If Cells(j, l).MergeCells Then
                         Cells(j, l).MergeArea.ClearContents
                      Else
                         Cells(j, l).ClearContents
                       End If
                Else: End If
            Next l
            'build the range which will be hidden
            If rngHide Is Nothing Then
                Set rngHide = ws.Cells(j, 1)
            Else
                Set rngHide = Application.Union(rngHide, ws.Cells(j, 1))
            End If

       Else: End If
    Next j

    'anything to hide?  Hide it.
    If Not rngHide Is Nothing Then rngHide.EntireRow.Hidden = True

    With Sheets("Inputs")
    .Select
    .Range("Spendinginput").Select
    End With

    Application.ScreenUpdating = True
    End With
End Sub

1 个答案:

答案 0 :(得分:3)

所有对Cells属性的引用(如下所示)都需要添加一个点。

此:

Cells(j, l).ClearContents

需要这样:

.Cells(j, l).ClearContents