VBA崩溃Excel

我正在使用excel和VBA来添加一个单元格,使用下表中的内容。 从表1中收集数据。它的代码首先检查B(2)列中的选项是否为op1 ,然后读取列A(1)的内容并追加单元格D2(表2中的op1下方)。

然后使用循环遍历表1中的所有值,然后应该连续填充表2,直到超出设置的限制(3)。

表格1:

 AB --- --- text op1 textt op2 text op1 

表2:

 D --- op1 *** The Cell I want to Append *** 

我正在使用的代码如下。

 Sub ProcOne() OpColOne = 4 TextColMain = 1 OpColMain = 2 i = 1 Do Until i > 3 If Cells(i, OpColMain) = "op1" Then Cells(2, OpColOne) = Cells(2, OpColOne) & vbNewLine & Cells(i, TextColMain) i = i + 1 End If Loop End Sub 

 Option Explicit Sub ProcOne() Dim OpColMain As Long Dim TextColMain As Long Dim opColOne As Long Dim i As Long opColOne = 4 TextColMain = 1 OpColMain = 2 i = 1 Do Until i >= 3 With ActiveSheet If .Cells(i, OpColMain) = "op1" Then .Cells(2, opColOne) = .Cells(2, opColOne) & vbNewLine & .Cells(i, TextColMain) End If i = i + 1 End With Loop End Sub 

您需要Option Explicit来确保正确地声明所有variables。 你需要With ActiveSheet ,因为没有它,你可能会在Excel中出错。 因此,你声明.Cells的ActiveSheet,而不仅仅是Cells 。 请参阅Microsoft信息在这里: Worksheet.Cells属性(Excel) 。

最后但并非最不重要的i = i + 1应该在循环之外,以确保我们离开无限循环。 或者里面,根据代码和案例。 但在这种情况下,我们只有3条线 – 外面。

最后编辑 – 如果你想循环3次,使用Do Until i >= 3 ,否则你只循环两次。