【问题标题】:Loop Crashing Excel VBA循环崩溃Excel VBA
【发布时间】:2016-06-26 04:20:58
【问题描述】:

我在让我的代码通过其条件循环并停止运行时遇到问题。这是我所拥有的:

  Do While True
    Dim i As Integer
    i = 2
    If Cells(i, 1).Value <> "" And Not IsError(Cells(i, 2).Value) Then
        Range(Cells(i, 1), Cells(i, 22)).Copy
        Range(Cells(i, 1), Cells(i, 22)).PasteSpecial
        i = i + 1
    Else
        Exit Do
    End If
  Loop

我要做的是让程序检查一个单元格是否为空,如果另一个单元格中没有错误,如果满足该条件,则程序将复制某一行并将其重新粘贴为它的值,因为该行中的某些单元格是一个公式。由于某种原因,循环没有退出并且 Excel 崩溃,我是否遗漏了什么?

【问题讨论】:

  • i = 2放在Do While True上方的循环之外。
  • 你的 i 值永远不会改变。 i = i + 1 没问题,但是你每次循环都将它重置为 2。
  • 你的循环在 true 时退出,所以我建议永远不会满足条件。

标签: vba excel while-loop crash


【解决方案1】:

i = 2 应该在外面

Dim i As Integer
i = 2
Do While True

If Cells(i, 1).Value <> "" And Not IsError(Cells(i, 2).Value) Then
    Range(Cells(i, 1), Cells(i, 22)).Copy
    Range(Cells(i, 1), Cells(i, 22)).PasteSpecial
    i = i + 1
Else
    Exit Do
End If
Loop

【讨论】:

    【解决方案2】:

    两点:

    1. i = 2 必须在 while 循环之外。
    2. 不要使用 CopyPasteSpecial。以后使用剪贴板会带来很多问题。此外,PasteSpecial 喜欢您具体说明您正在使用的“什么”PasteSpecial 操作。而是直接赋值。

    将 i 调为整数,将数据集调为变体

    i = 2
    Do While True
        If Cells(i, 1).Value <> "" And Not IsError(Cells(i, 2).Value) Then
            'This seems silly, but it overwrites the cell with its value.
            Dataset = Range(Cells(i, 1), Cells(i, 22)).Value
            Range(Cells(i, 1), Cells(i, 22)).Value = Dataset
            i = i + 1
        Else
            Exit Do
        End If
      Loop
    

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2017-12-01
      • 2019-05-04
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      相关资源
      最近更新 更多