2017-04-19 123 views
2

我正在使用excel和VBA使用下表中的内容追加单元格。数据从表1中收集。它的代码首先检查B(2)列中的选项是op1它应该读取列A(1)的内容并附加单元格D2(表2中的op1以下)。VBA崩溃Excel

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

表1:

A  B 
--- --- 
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 

回答

3
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,以确保您正确声明所有变量。 您需要With ActiveSheet,因为没有它,您可能会在Excel中发生错误。因此,你 宣布.Cells到ActiveSheet,而不仅仅是Cells。请在此处查看微软的信息:Worksheet.Cells Property (Excel)

最后但并非最不重要i = i + 1应该在循环之外,以确保我们离开无限循环。或者在里面,取决于代码和案例。但在这种情况下,我们只有3条线 - 外面。最后编辑 - 如果你想循环3次,使用Do Until i >= 3,否则你只循环两次。

+0

@ A.S.H - 我同意。 – Vityata