2016-12-06 63 views
1

我在這個輸出中遇到問題。它似乎主要是工作,但我錯過了某個步驟。每個PDF的VBA嵌套

在下面的代碼: K4至K7是數字代碼和L4〜L7的是一些詞的名字 - 4條 我試着去其輸出到PDF,它應該只有4條記錄但由於某種原因,它輸出重複版本,共計16個。我知道這些循環是錯誤的。有任何解決這個問題的方法嗎?

Sub foreachtest2() 
Application.ScreenUpdating = False 
Dim c As Range 
Dim f As Range 



Sheets("Lookup Table").Range("K4:K7").Name = "Rng" 
Sheets("Lookup Table").Range("L4:L7").Name = "RngName" 


For Each c In Range("Rng") 
    For Each f In Range("RngName") 

    Sheets("Site Report").Select 
    Range("D7").Select 
    ActiveCell.FormulaR1C1 = c.Value 




Sheets("Site Report").Select 
Range("A1:M78").Select 
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
     "C:\path" & f.Value & c.Value & ".pdf", Quality:=xlQualityStandard, _ 
     IncludeDocProperties:=True, IgnorePrintAreas:=False 

Next 
Next 


    Application.ScreenUpdating = True 

End Sub 

回答

3

你不需要兩個循環,只有一個迭代的K列。在每次迭代中,通過使用「偏移量」檢索L中的對應值。

For Each c In Range("Rng") 
    Set f = c.Offset(, 1) 
    ' ... 
    ' do the work. I cant verify if the code inside your loop 
    ' does the intended work. But this quick fix should solve the 
    ' 16 values issue. Now you should have only 4 records to work on. 
Next 
+1

它的確如您所描述的那樣工作,使用偏移量可以達到我需要的效果。正如你所建議的那樣,我不需要另一個。非常感激。 – penfold255