2014-05-07 17 views
0

該子代將舊數據(Sheet3)與新(Sheet1)進行比較。新數據可以出現在範圍內的任何地方,但中間不會有空行。每次執行時,我的代碼都會調用sndPlaySound32,即使沒有新數據。爲什麼?如果使用xldirections設置,範圍始終是一些東西?空範圍執行爲不是Nothing

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 
+2

'如果不rngInput是Nothing Then'不檢查範圍是否有沒有數據,但檢查是否' rngInput' _refers_到'Range'對象。你可以這樣使用:'如果Application.Counta(rngInput)Then' –

+0

你說得對!謝謝。如果你把它作爲答案,我會勾選它:) – hovde

回答

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