2014-02-19 226 views
0

我有兩個文檔同時打開,一個是空白模板,另一個是舊Excel文件,我試圖將數據轉換爲新的模板格式。我正在編寫一個宏來循環訪問源文件中的指定列,並傳遞任何非空白單元格的值。這是我當前的代碼:VBA - 嵌套「For Each」連續循環

For Each TargetCell In RevisedFAA.Sheets("Repair Instruction").Range("K17:W40") 'Template 
     For Each SourceCell In Range(FAA_User.AppColumn1.Value) 'Source file range 

CheckSource: 
     If SourceCell = "" Then 
      GoTo NextSourceCell 'if the cell in the source file is blank, skip to the next cell 
     Else 
      TargetCell.Value = SourceCell.Value 
      GoTo NextTargetCell 'if the cell in the source file has data, transfer that data over to the template. 
     End If 
NextSourceCell: 
     Next SourceCell 

NextTargetCell: 
     Next TargetCell 
     GoTo NextSourceCell 

問題是當有源文件中的數據,它轉移到模板,然後循環重複,由於我Next TargetCell線,其將所有空白的價值使用數據將模板中的單元格移動到第一個SourceCell。有沒有更好的方法來解決這個問題?

回答

0

如果你運行一個循環,再加上一個增量,代碼結構將是簡單得多:

Dim lLoop As Long, lMaxLoop As Long, rgTarget As Range 
Dim sourceCell As Range 

Set rgTarget = RevisedFAA.Sheets("Repair Instruction").Range("K17:W40") 
lLoop = 1 

Set lMaxLoop = rgTarget.Cells.Count 

For Each sourceCell In Range(FAA_User.AppColumn1.Value) 'Source file range 

    If sourceCell <> "" Then 
     rgTarget.Cells(lLoop).Value = sourceCell.Value 
     lLoop = lLoop + 1 
     If lLoop > lMaxLoop Then Exit For 
    End If 

Next sourceCell 
+1

使用'退出For'是如此的不是「轉到」在這種情況更爲乾淨.. – enderland

+0

@nutsch感謝您的建議!出於某種原因,我在'1Loop = 1'行或者在我的情況下'i = 1'上收到了「Object required」錯誤。 – CJK

+1

@CJK從該行刪除「set」。你只能用對象而不是基本變量類型來設置。 – enderland