VisualBasic所附带的报表生成器-CrystalReports,功能强大,能完成大部分报表的制作。但在某些情况下,用CrystalReports却很难作出报表来。例如,根据用户输入不同的过滤(Filter)条件,将产生不同的虚拟表,此时用CrystalReports制作报表就勉为其难了,在这种情况下,可使用VB提供的Printer对象来予以解决。
下面是本人在给单位开发一个产品销售情况统计分析软件的过程中,使用Printer对象从Recordset对象的虚拟表中打印数据的通用代码:
Sub PrintRecordset(recRecordset as Recordset) Dim LeftMargin As Integer Dim HeadTopPosition As Integer Dim FieldNum As Integer Dim PageCounter As Integer Dim MyRecordset As Recordset Const FooterTopPosition=24
Set MyRecordset=recRecordset PageCounter = 1 '设置Printer对象坐标的度量单位为厘米 Printer.ScaleMode = vbCentimeters
LeftMargin = 1.5 HeadTopPosition = 2
'定义打印页左上角的X坐标和Y坐标,通过改变ScaleLeft和ScaleTop的值,可改变打印页的左边距和上边距
Printer.ScaleLeft = -LeftMargin Printer.ScaleTop = -HeadTopPosition
Printer.Font.Name = "Times New Roman" Printer.Font.Size = 12
Printer.Print "Lovesoft Corp." Printer.Print ""
If MyRecordset.EOF And MyRecordset.BOF Then MsgBox "No Record At Presend!", vbCritical + vbOKOnly, "Print Error" Exit Sub End If MyRecordset.MoveFirst
Do Until Printer.CurrentY > FooterTopPosition
'Print the fields of the recordset in sequence For FieldNum = 0 To MyRecordset.Fields.Count - 1 Printer.Print MyRecordset.Fields (FieldNum).Name & _ ": " & _ MyRecordset.Fields(FieldNum).Value If Printer.CurrentY > FooterTopPosition Then Printer.CurrentX = 8 Printer.Print "Page: " & PageCounter '创建多页文档 Printer.NewPage PageCounter = PageCounter + 1 End If Next FieldNum
MyRecordset.MoveNext If MyRecordset.EOF Then Exit Do '在记录之间空一行 Printer.Print "" Loop
'Print the Page number as a footer Printer.CurrentX = 8 Printer.CurrentY = FooterTopPosition Printer.Print "Page: " & PageCounter '将输出送到打印机 Printer.EndDoc End Sub
调用上述PrintRecordset通用过程相当方便,下面是通过cmdPrint按钮的Click事件进行调用的一个实例:
Private Sub cmdPrint_Click() PrintRecordset Data1.Recordset End Sub |