所以我是vba的新手,我試圖讓宏來比較單元格,並在它旁邊的列中輸出一個計數器。這裏是我的代碼:Excel VBA很多問題
Sub Duplicate_Count()
'Find the last used row in a Column: column A in this example
Dim LastRow As Long
Dim value1 As String
Dim value2 As String
Dim counter As Integer
counter = 1
With ActiveSheet
LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row
End With
'Search down row for duplicates
Dim i As Long
For i = 1 To LastRow
'Sets value1 and value2 to be compared
value1 = Worksheets("Sheet1").Cells(i, "L").Value
value2 = Worksheets("Sheet1").Cells(i + 1, "L").Value
'If values are not diferent then counter will not increment
If value1 <> value2 Then
counter = counter + 1
End If
'Sets the n colom to count, duplicates should not increment the counter
Sheet1.Cells(i, "N") = counter
Next i
末次
好了,所以這段代碼運行,它看起來它的工作原理,列「N」開始填充,但程序凍結了,我不知道如果僅僅是因爲文件太大以致需要很多時間,或者如果出現錯誤。如果我重新啓動程序,我得到運行時錯誤'-2147417848(80010108)':對象「範圍」的方法'_Default'失敗。只是讓愚蠢的錯誤
編輯: 子Duplicate_Count() 「查找列中的最後一次使用的行:A列在這個例子中
Dim LastRow As Long
Dim value1 As String
Dim value2 As String
Dim counter As Long
counter = 0
Dim sht As Worksheet
Set sht = Worksheets("Sheet1")
With ActiveSheet
LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row
End With
'Search down row for duplicates
Dim i As Long
For i = 1 To LastRow
'Sets value1 and value2 to be compared
value1 = Worksheets("Sheet1").Cells(i, "L").Value
value2 = Worksheets("Sheet1").Cells(i + 1, "L").Value
'If values are not diferent then counter will not increment
If value1 <> value2 Then
counter = counter + 1
End If
'Sets the n colom to count, duplicates should not increment the counter
sht.Cells(i, "N") = counter
Next i
末次
此代碼崩潰每次,和偶爾會給我一個錯誤:運行時錯誤'-2147417848(80010108)':對象「Range」的方法'_Default'失敗。我不知道如何解決這個問題......甚至是什麼意思。
我注意到的第一個潛在問題是您每次循環時都將計數器設置爲1,您是否希望這樣做?同時,每當你循環時,你都不需要'調暗'每個變量。 – Dexloft
不,我意識到可以將其移出循環,謝謝! – Josh
也許你可以使用簡單= COUNTIF($ A $ 1:$ A $ 1000,A1)? – jkpieterse