EXCEL VBA:创build一个简单的循环来重复每一行的处理

我知道这似乎是一个非常简单的问题,但我尝试了不同的方法来创build一个循环,将做我在找什么:基本上我有一个Excel列表(4列)(未知的行数),我想input数据。 然后将这些数据镜像到第二张纸上,其中包含用于创build多个PDF文件的“打印devise”。 问题是:我尝试了4天,现在创build一个循环,并没有取得任何成就!

如果你能帮助我,这是数据input: SCREENSHOT

Public Sub InputData() Dim strCap As String strCap = Sheets("INPUT").Cells(4, 3).Value Label1.Caption = strCap Dim strCap2 As String strCap2 = Sheets("INPUT").Cells(4, 5).Value Label2.Caption = strCap2 If Sheets("INPUT").Cells(4, 4) = "OE" Then Image1.Picture = LoadPicture(ActiveWorkbook.Path & "\OE_Logo.jpg") Else Image1.Picture = LoadPicture(ActiveWorkbook.Path & "\SF_Logo.jpg") End If If Sheets("INPUT").Cells(4, 6) = "OE" Then Image2.Picture = LoadPicture(ActiveWorkbook.Path & "\OE_Logo.jpg") Else Image2.Picture = LoadPicture(ActiveWorkbook.Path & "\SF_Logo.jpg") End If Application.Calculate Call PrintPDF End Sub Sub PrintPDF() Dim pdfjob As Object Dim sPDFName As String Dim sPDFPath As String '/// Change the output file name here! /// sPDFName = "Affidavit" & " " & Sheets("INPUT").Cells(4, 3) & "_" & Sheets ("INPUT").Cells(4, 5) & ".pdf" sPDFPath = ActiveWorkbook.Path & Application.PathSeparator 'Check if worksheet is empty and exit if so If IsEmpty(ActiveSheet.UsedRange) Then Exit Sub Set pdfjob = CreateObject("PDFCreator.clsPDFCreator") With pdfjob If .cStart("/NoProcessingAtStartup") = False Then MsgBox "Can't initialize PDFCreator.", vbCritical + _ vbOKOnly, "PrtPDFCreator" Exit Sub End If .cOption("UseAutosave") = 1 .cOption("UseAutosaveDirectory") = 1 .cOption("AutosaveDirectory") = sPDFPath .cOption("AutosaveFilename") = sPDFName .cOption("AutosaveFormat") = 0 ' 0 = PDF .cClearCache End With 'Print the document to PDF Sheets("AFFIDAVIT CREATOR").PrintOut Copies:=1, From:=1, To:=1, ActivePrinter:="PDFCreator" 'Wait until the print job has entered the print queue Do Until pdfjob.cCountOfPrintjobs = 1 DoEvents Loop pdfjob.cPrinterStop = False 'Wait until PDF creator is finished then release the objects Do Until pdfjob.cCountOfPrintjobs = 0 DoEvents Loop pdfjob.cClose Set pdfjob = Nothing End Sub 

我实际上想为每一行创build一个单一的PDF文件,所以这样做第4,5,6行等,直到VBA发现一个空行。

任何帮助将不胜感激,提前感谢我在Stackoverflowfind的所有帮助,并希望有所帮助!

谢谢,

雅尼克

一般来说,在VBA中创build一个循环的好方法包括以下步骤:

  1. 定义您想要循环的单元格的范围
  2. 将范围指定给一个variables(用Dim myRange as Range声明Dim myRange as Range
  3. 用这样的循环遍历范围的(单元格,行):
     Dim r as Range,myRange as Range
    设置myRange = Range(Sheet(“INPUT”)。cells(4,4),Sheet(“INPUT”)。cells(4,4).end(xlDown))
    对于myRange.Cells中的每个r
       turnRowIntoPdf r
    下一个

这将把myRange定义为从单元格(4,4)开始的范围 – 即D4 – 并且尽可能地远离有条目。 然后依次循环这些单元(D4,D5,D6,…),并用参数r (将依次为这些单元中的每一个)调用Sub turnRowIntoPdf 。 然后,您可以编写一个将此参数作为input的子文件,并创buildpdf。

认为你可以从那里pipe理它?