修改Excel VBA导出PDF代码:移除行10限制,循环至空行
修改后的VBA代码(循环至空行)
以下是调整后的代码,移除了固定循环到第10行的限制,改为自动识别Claims工作表中最后一行数据并循环处理:
'导出PDF' Sub ExportingPDF() Dim claimsSheet As Worksheet Dim reportSheet As Worksheet Dim lastRow As Long '新增变量存储最后一行行号 Set reportSheet = ActiveWorkbook.Sheets("Design") Set claimsSheet = ActiveWorkbook.Sheets("Claims") '获取Claims表中第一列最后一个非空行的行号(若第一列可能为空,可修改列号为其他必含数据的列)' lastRow = claimsSheet.Cells(claimsSheet.Rows.Count, 1).End(xlUp).Row '循环处理每一行数据' For i = 2 To lastRow '读取Claims表中的数据' SOrganization = claimsSheet.Cells(i, 1) SBilling_Provider = claimsSheet.Cells(i, 2) SDOS = claimsSheet.Cells(i, 3) SMRN = claimsSheet.Cells(i, 4) SPatient_Name = claimsSheet.Cells(i, 5) SAudit_Program = claimsSheet.Cells(i, 6) SAudit_Date = claimsSheet.Cells(i, 7) SAuditor_Initials = claimsSheet.Cells(i, 8) SChief_Complaint = claimsSheet.Cells(i, 9) SMedically_Appropriate_History = claimsSheet.Cells(i, 10) SMedically_Appropriate_Exam = claimsSheet.Cells(i, 11) '将数据写入Design表对应位置' reportSheet.Cells(1, 3).Value = SOrganization reportSheet.Cells(2, 3).Value = SMRN reportSheet.Cells(3, 3).Value = SPatient_Name reportSheet.Cells(4, 3).Value = SAudit_Program reportSheet.Cells(5, 3).Value = SAuditor_Initials reportSheet.Cells(6, 3).Value = SMedically_Appropriate_History reportSheet.Cells(2, 7).Value = SBilling_Provider reportSheet.Cells(3, 7).Value = SDOS reportSheet.Cells(4, 7).Value = SAudit_Date reportSheet.Cells(5, 7).Value = SChief_Complaint reportSheet.Cells(6, 7).Value = SMedically_Appropriate_Exam '保存为PDF' reportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ "C:\Users\ortegar\Pictures\" & SMRN, Quality:=xlQualityStandard, _ IncludeDocProperties:=True, IgnorePrintAreas:=False, _ OpenAfterPublish:=False Next i End Sub
关键修改说明:
- 新增
lastRow变量,通过Cells(Rows.Count, 1).End(xlUp).Row获取Claims表中第一列最后一个非空行的行号,确保覆盖所有有效数据行。 - 将原固定循环范围
For i = 2 To 10改为For i = 2 To lastRow,实现动态循环至最后一行数据。 - 若你的数据中第一列(Organization)可能存在空行,可将代码中的列号
1改为其他必然包含数据的列(比如MRN所在的第4列,即改为Cells(claimsSheet.Rows.Count, 4).End(xlUp).Row)。
内容的提问来源于stack exchange,提问作者reallycow21
相关产品推荐
相关产品推荐

