2017-04-19 122 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