2017-07-07 315 views
4

所以我試圖刪除C列中有重複的行。這是大約700條記錄的列,但是這個值隨使用的不同數據而異,因此我實現了一個「LastRow」功能。這裏是我的代碼:VBA Excel刪除重複行

Public Function LastRowInCRC() As Long 

    Dim wsCRC As Worksheet 
    Set wsCRC = Worksheets("CRC") 

    With wsCRC 
     LastRowInCRC = .Cells(.Rows.Count, "C").End(xlUp).Row 
    End With 

End Function 

Sub DeleteDupRowsCRC() 

    Dim wsCRC As Worksheet 
    Set wsCRC = Worksheets("CRC") 

    Dim lrowcrc As Long 
    lrowcrc = CRC.LastRowInCRC 

    'Debug.Print "C8:C" & lrowcrc 

    With wsCRC 

     .Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3) 

    End With 

End Sub 

我得到的「應用程序定義或對象定義的」在下面的行,當我一步一步地調試錯誤:

.Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3) 

任何想法什麼問題呢?我將「C8:C」& lrowcrc稱爲即時窗口,它被註釋掉了,它給了我正確的範圍值,所以我不認爲問題在那,但我找不到什麼錯誤......任何幫助都很大讚賞。

回答

3

通常,將Array(3)更改爲Array(1),它可能會有效。


不一般:對我來說,下面的工作,除去在C列中的重複確保您的第一個工作表的工作:

Option Explicit 

Public Function LastRowInCRC() As Long 

    Dim wsCRC As Worksheet 
    Set wsCRC = Worksheets(1) 

    With wsCRC 
     LastRowInCRC = .Cells(.Rows.Count, "A").End(xlUp).Row 
    End With 

End Function 

Sub DeleteDupRowsCRC() 

    Dim wsCRC As Worksheet 
    Set wsCRC = Worksheets(1) 

    Dim lrowcrc As Long 
    lrowcrc = LastRowInCRC 

    'Debug.Print "C8:C" & lrowcrc 

    With wsCRC 

     .Range("C1:C" & lrowcrc).RemoveDuplicates Columns:=Array(1) 

    End With 

End Sub 

在你的代碼,Array(3)意味着你應該有在.Range中至少有三列。但你只有C列。因此,它會出錯。要與Array(3)一起工作,請寫A1:C,它會起作用。

1

我認爲你的範圍無效的語法。 請試試這個下面

With wsCRC 
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).Select 
    .Range(Cells(8, 3), Cells(lrowcrc, 3)).RemoveDuplicates Columns:=1, Header:=xlYes 

End With 

在旁邊,我想你應該使用下面

lrowcrc = LastRowInCRC

或使用此代碼來獲取最後一行

wsCRC。[C8] .SpecialCells(xlCellTypeLastCell).Row