Control Excel generated report with VB

xiaoxiao2021-03-06  40

As a simple, systematic Windows application development tool, Visual Basic 5 has powerful data processing functions, providing a variety of data access methods, convenient access to various databases such as Microsoft SQL Server, Oracle, XBase, Widely used to establish a variety of information management systems. However, VB lacks sufficient, in line with the data table output function of Chinese habits, although the report can be output using the Crystal Report control and the Crystal Reports program, but it is very troublesome, and the Chinese processing capability is not ideal. Excel has a powerful feature as a table processing software of MICORSOFT, we can use VB5 to write a program that directly control Excel operations, and the method is to obtain the EXCEL 97 control handle with VB's OLE automation technology to directly control the Excel 97. operating. The following is given: first build a form (Form1) Add a Data control and a button in the form, reference the Microsoft Excel type library: Select the "Reference" bar from the Project menu; select Microsoft Excel 8.0 Object Library Select "OK". Add: in the Form's LOAD event:

Data1.DatabaseName = Database Name DATA1.Recordsource = Table name Data1.refresh Add to Click event in the button

Dim Irow, Icol As Integer Dim Irowcount, Icolcount As Integer Dim Fieldlen () "field length value stored Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Set xlApp = CreateObject (" Excel.Application ") Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets (1) With Data1.Recordset.MoveLast If .RecordCount <1 Then MsgBox ( "Error no record!") Exit Sub End If Irowcount = .RecordCount "Total number of records Icolcount = .Fields.count "Total number redim fieldlen (icolcount) .Movefirst for irow = 1 to irowcount 1 for iCol = 1 To icolcount Select Case Irow Case 1" In Excel's first line plus title xlsheet.cells (Irow, Icol) .Value = .fields (ICOL - 1) .Name Case 2 "Pretty Group Fieldlen () to the first record field length if ISNULL (.fields (ICOL - 1)) = True Then Fieldlen (ICOL) = LeNB (.fields (Icol - 1) "" If the field value is null, set the value of the array Filelen (ICOL) to the width Fieldlen (ICOL) = lenb (.fields (Icol - 1)) End if xlsheet.columns (icol) .COLUMNWIDTH = FIELDLEN (ICOL) "Excel column width is equal to field length xlsheet.cells (irow, ICOL) .Value = .fields (ICOL - 1)" Write a field value Case Else Fieldlen1 = lenb (.fields (Icol - 1)) IF in the cells of Excel. FieldLen (ICOL)

转载请注明原文地址:https://www.9cbs.com/read-76524.html

New Post(0)