所以我是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