2014-02-19 3 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"을 제거하십시오. 기본 변수 유형이 아닌 객체에만 set을 사용합니다. – enderland