【问题标题】:Variable not defined problem with option explicit macro选项显式宏的变量未定义问题
【发布时间】: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。

标签: excel vba


【解决方案1】:

作为我之前的安德烈亚斯: 您必须定义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

这应该可以解决问题:)

【讨论】:

  • S/he 的意思是 x,而不是 i。基本上,发生错误是因为您使用 x 作为循环计数器:但您还没有将其调暗。您需要声明您使用的每个变量,循环计数器变量也不例外。 Lonolian 是正确的,但只是打错了,使用“i”而不是“x”。
  • 谢谢 Darren Bartup-Cook 和 Chris Melville
猜你喜欢
  • 2017-09-22
  • 2019-09-21
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2018-01-08
  • 2021-05-30
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多