代码:
Private Sub Command455_Click()
Dim filename As String
Dim filepath As String
filename = Me.LAST_NAME & "," & " " & Me.FIRST_NAME & "," & " " & Me.STUDENT_ID
filepath = "C:\Users\ddennis1\Desktop\" & filename & ".pdf"
DoCmd.OpenReport "Humanities_MiniDips", acViewPreview, , "[Student_ID]=Forms!DIPLOMAS_EXPRESS!STUDENT_ID"
DoCmd.OutputTo acOutputReport, "Humanities_MiniDips", acFormatPDF, filepath
MsgBox "Graduate exported", vbInformation, "Save confirmed"
End sub
上面的编码很好用,但是一次只能根据表格上显示的学生证导出一个PDf。
我想根据上述编码,使用另一个命令按钮从数据库中导出多个已命名的PDF。
该报告称为“ Humanities_Minidips”,记录源称为“ Humanites”
我认为完成此任务需要某种循环机制。
任何人都对如何向前发展有任何想法?
您是正确的,您需要一个循环来实现所需的行为。您还需要一个包含学生姓名和ID的表,您可以查询该表以提供要循环通过的列表。
下面的代码将您的大部分代码包装在一个简单的循环中,该循环将记录存储在名为“ STUDENTS”的表中,并为每个学生输出PDF。
' change NewButton to the name of your new button for printing all students
Private Sub NewButton_Click()
Dim filename As String
Dim filepath As String
Dim db as Database
Set db = CurrentDb
Dim rs as Recordset
' change the name of the table to match your student table vvvvvvvv
Set rs = db.OpenRecordset("SELECT FIRST_NAME, LAST_NAME, STUDENT_ID FROM STUDENTS", dbOpenSnapshot)
While not rs.EOF
' reference the desired field names in the current row
filename = rs("LAST_NAME") & "," & " " & rs("FIRST_NAME") & "," & " " & rs("STUDENT_ID")
filepath = "C:\Users\ddennis1\Desktop\" & filename & ".pdf"
DoCmd.OpenReport "Humanities_MiniDips", acViewPreview, , "
[Student_ID]=" & rs("STUDENT_ID")
DoCmd.OutputTo acOutputReport, "Humanities_MiniDips", acFormatPDF, filepath
' This line logs the export for each student, this will help you with
' troubleshooting for specific students if necessary. The log can be found
' by pressing Ctrl + G while in the VBA editor in Access.
Debug.Print "PDF for " & rs("FIRST_NAME") & " " & rs("LAST_NAME") & " exported"
' move to the next record, CRITICAL or else you will loop forever
rs.MoveNext
Wend
' indicate that export is finished
MsgBox "Graduates exported", vbInformation, "Save confirmed"
End sub