空范围执行为无结果

时间:2014-05-07 09:06:57

标签: vba

此子将旧数据(Sheet3)与new(Sheet1)进行比较。新数据可以出现在范围内的任何位置,但两者之间从不存在空行。我的代码每次执行时都会调用sndPlaySound32,即使没有新数据也是如此。为什么?如果使用xldirections设置范围总是一个范围?

    Public Declare Function sndPlaySound32 _
    Lib "winmm.dll" _
    Alias "sndPlaySoundA" ( _
    ByVal lpszSoundName As String, _
    ByVal uFlags As Long) As Long 


    Sub CheckNew()
    Dim I As Long
    Dim j As Long
    Dim rngInput As Range
    Dim wksInput As Worksheet
    Dim VarSheet1 As Variant
    Dim VarSheet2 As Variant

    Set wksInput = ThisWorkbook.Worksheets("Sheet1")
    Set rngInput = ThisWorkbook.Worksheets("Sheet1").Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
    VarSheet1 = ThisWorkbook.Worksheets("Sheet1").Range("C1:D" & Cells(Rows.Count, "D").End(xlUp).Row)
    VarSheet2 = ThisWorkbook.Worksheets("Sheet3").Range("C1:D" & Cells(Rows.Count, "D").End(xlUp).Row)


        For I = 1 To UBound(VarSheet2, 1)
            For j = 1 To UBound(VarSheet1, 1)
                If VarSheet1(I, 1) = VarSheet2(j, 1) Then
                wksInput.Rows(I).EntireRow.ClearContents
                Else
                'New data
                End If
           Next j
        Next I
        If Not rngInput Is Nothing Then
        sndPlaySound32 "C:\Windows\Media\Ring03.wav", &H0
        End If
    End Sub

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的那样,

If Not rngInput Is Nothing Then

不检查范围是否没有数据,但检查rngInput 是否将引用到Range对象。

你可以改用这个:

If Application.CountA(rngInput) Then
   sndPlaySound32 "C:\Windows\Media\Ring03.wav", &H0
End If

或更可靠:

If Not rngInput Is Nothing Then
   If Application.CountA(rngInput) Then
      sndPlaySound32 "C:\Windows\Media\Ring03.wav", &H0
   End If
End If
相关问题