----VisualBasic所附帶的報表生成器-CrystalReports,功能強大,能完成大部分報表的制作。但在某些情況下,用CrystalReports卻很難作出報表來。例如,根據用戶輸入不同的過濾(Filter)條件,將產生不同的虛擬表,此時用CrystalReports制作報表就勉為其難了,在這種情況下,可使用VB提供的Printer對象來予以解決。
----下面是本人在給單位開發一個產品銷售情況統計分析軟件的過程中,使用Printer對象從Recordset對象的虛擬表中打印數據的通用代碼:
SubPrintRecordset(recRecordsetasRecordset)
DimLeftMarginAsInteger
DimHeadTopPositionAsInteger
DimFieldNumAsInteger
DimPageCounterAsInteger
DimMyRecordsetAsRecordset
ConstFooterTopPosition=24
SetMyRecordset=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="TimesNewRoman"
Printer.Font.Size=12
Printer.Print"LovesoftCorp."
Printer.Print""
IfMyRecordset.EOFAndMyRecordset.BOFThen
MsgBox"NoRecordAtPresend!",
vbCritical vbOKOnly,"PrintError"
ExitSub
EndIf
MyRecordset.MoveFirst
DoUntilPrinter.CurrentY>FooterTopPosition
'Printthefieldsoftherecordsetinsequence
ForFieldNum=0ToMyRecordset.Fields.Count-1
Printer.PrintMyRecordset.Fields
(FieldNum).Name&_
":"&_
MyRecordset.Fields(FieldNum).Value
IfPrinter.CurrentY>FooterTopPositionThen
Printer.CurrentX=8
Printer.Print"Page:"&PageCounter
'創建多頁文檔
Printer.NewPage
PageCounter=PageCounter 1
EndIf
NextFieldNum
MyRecordset.MoveNext
IfMyRecordset.EOFThenExitDo
'在記錄之間空一行
Printer.Print""
Loop
'PrintthePagenumberasafooter
Printer.CurrentX=8
Printer.CurrentY=FooterTopPosition
Printer.Print"Page:"&PageCounter
'將輸出送到打印機
Printer.EndDoc
EndSub
----調用上述PrintRecordset通用過程相當方便,下面是通過cmdPrint按鈕的Click事件進行調用的一個實例:
PrivateSubcmdPrint_Click()
PrintRecordsetData1.Recordset
EndSub->