Excel|visual Excel is a very good report making software, with VBA can control its generation of excellent reports, this article by adding a query statement, that is, the ability to get external data in Excel to quickly capture data from a query statement to Excel, It's a lot more than a way to write data in each cell.
Add the following to a module, and the screen calls the following Exportoexcel ("Select * FROM table") to export it to excel
Public Function Exportoexcel (Stropen as String)
'*********************************************************
' * Name: Exportoexcel
' * Function: Export data to Excel
' * Usage: exportoexcel (SQL query string)
'*********************************************************
Dim Rs_data as New ADODB. Recordset
Dim Irowcount as Integer
Dim Icolcount as Integer
Dim xlapp as New excel.application
Dim Xlbook as Excel.Workbook
Dim Xlsheet as Excel.Worksheet
Dim XLQuery as Excel.querytable
With Rs_data
If. State = adStateOpen Then
. Close
End If
. ActiveConnection = Cn
. CursorLocation = adUseClient
. CursorType = adOpenStatic
. LockType = adLockReadOnly
. Source = Stropen
. Open
End With
With Rs_data
If. RecordCount < 1 Then
MsgBox ("no record!")
Exit Function
End If
' Total records
Irowcount =. RecordCount
' Total fields
Icolcount =. Fields.Count
End With
Set xlapp = CreateObject ("Excel.Application")
Set xlbook = Nothing
Set xlsheet = Nothing
Set xlbook = Xlapp.workbooks (). Add
Set xlsheet = xlbook.worksheets ("Sheet1")
Xlapp.visible = True
' Add query statements, import Excel data
Set xlquery = XlSheet.QueryTables.Add (Rs_data, Xlsheet.range ("A1"))
Xlquery.fieldnames = True ' Displays field names
Xlquery.refresh
With Xlsheet
. Range (. Cells (1, 1),. Cells (1, Icolcount)). Font.Name = "Blackbody"
' Set title to bold text
. Range (. Cells (1, 1),. Cells (1, Icolcount)). Font.Bold = True
' Title font Bold
. Range (. Cells (1, 1),. Cells (Irowcount + 1, icolcount)). Borders.LineStyle = xlcontinuous
' Set table border style
End With
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.