【发布时间】:2019-01-02 07:46:01
【问题描述】:
我有下面的代码,它适用于一张简单的表格。如果我尝试将它合并到我的宏中,这是选项显式的,那么它会引发一个错误,即变量 x 未定义。
尝试了各种 Dim,但都没有成功。对此很陌生,所以我认为我遗漏了一些东西,对你们来说可能相当明显
Sub FillDuplicates()
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row 'find last row in column A
For x = 1 To lastrow
If Cells(x, 1).Value = 0 Then 'Find initial 0 value
If Cells(x + 1, 1).Value = 0 Then 'Compares cell against previous cell
Cells(x + 1, 1).Value = "" 'If matches, sets value as nothing
End If
End If
Next x
End Sub
这标识了列中存在多个连续 0 值的位置。然后它保留第一个并删除其他的,然后移动到下一个组,依此类推。
【问题讨论】:
-
x 在我看来就像一个整数。所以试试
Dim x as Interger或者可能很长,这取决于你期望有多少行。如果我没记错的话,整数的最大值约为 32000 -
x从 1 变为lastrow,其中lastrow是Long。所以x也应该是Long。所以Dim x As Long在For x = 1 To lastrow之前。 -
肯定是
Long,因为它使用的行号可能超过Integer的限制。另外,因为lastrow被定义为Long,所以遍历lastrow中每个值的变量也应该是Long。