【发布时间】:2018-07-24 02:39:11
【问题描述】:
所以我是 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)'的错误:对象“范围”的方法'_Default'失败。我不知道如何解决这个问题.. . 或者它甚至意味着什么。
【问题讨论】:
-
我注意到的第一个潜在问题是您每次循环时都将计数器设置为 1,您希望它这样做吗?同时,你不需要每次循环时需要到
Dim每个变量 -
不,我意识到可以将其移出循环,谢谢!
-
您可以使用简单的 =COUNTIF($A$1:$A$1000,A1) 吗?
-
好的,Dexloft 似乎已经修复了它。这是一个巨大的文件,所以需要很长时间才能完成,如果我有任何其他问题,我会告诉你。再次感谢!
-
jkpieterse,这可能会起作用,但是我要运行它的文件会改变长度,我宁愿不必编辑我需要运行宏的每个文件的函数。如果我明白的话您发布的内容...