循环崩溃的Excel VBA

我一直在让我的代码运行通过条件循环和停止的问题。 这是我有什么:

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崩溃,我错过了什么?

我= 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 

两点:

  1. i = 2必须在while循环之外。
  2. 不要使用CopyPasteSpecial 。 使用剪贴板将在以后出现很多问题。 此外,PasteSpecial喜欢你具体的“什么”你使用的PasteSpecial行动。 而是直接赋值。

昏暗我作为整数,数据集作为变种

 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