选项显式宏的变量未定义问题

时间:2019-01-02 07:46:02

标签: excel vba

我有以下适用于简单工作表的代码。如果我尝试将其合并到我的宏(该宏是显式选项)中,则将引发错误,即未定义变量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值。然后,它保留第一个,删除其他,然后移到下一个组,依此类推。

1 个答案:

答案 0 :(得分:0)

就像安德里亚斯在我面前一样: 您必须定义x变量:

Sub FillDuplicates()
Dim lastrow As Long

Dim x as Integer 'if you have more 32767 rows to check then use double which is good for 1.79769313486231570E+308

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

这应该可以解决问题:)