|
|
MS Excel - Экспорт Данных в Excel c простым форматированием "шапки"
Private Function ExportDataToExcel(Optional sPathToSave$) As String
Dim sVal$
Dim objWrkBk As Object, objWrkSht As Object
Dim rst As DAO.Recordset
Dim i As Integer
Dim objExcelApp As Object
On Error GoTo ExportDataToExcel_Err
If sPathToSave = "" Then sPathToSave = CurrentProject.Path & "\test01.xls"
sVal = "SELECT Id, DateCreate, DateUpdate, Owner, Name FROM MSysObjects " & vbCrLf & _
"WHERE ((Flags=0) AND (Type=1)) ORDER BY Name;"
Set rst = CurrentDb.OpenRecordset(sVal, dbOpenSnapshot)
With rst
If .BOF = True And .EOF = True Then
MsgBox "Запрос не вернул записей, экспорт прекращён!", vbExclamation, "Ошибка экспорта данных"
GoTo ExportDataToExcel_End
End If
End With
If Dir(sPathToSave) <> "" Then Kill sPathToSave
If objExcelApp Is Nothing Then
Set objExcelApp = CreateObject("Excel.Application")
End If
Set objWrkBk = objExcelApp.Workbooks.Add
Set objWrkSht = objWrkBk.ActiveSheet
objWrkSht.Rows(1).RowHeight = 24
For i = 1 To rst.Fields.Count
With objWrkSht.Cells(1, i)
If i = 1 Then
.Value = "No"
Else
.Value = rst.Fields(i - 1).Name
End If
Select Case i
Case 1 To 4
.ColumnWidth = 14
Case 5
.ColumnWidth = 60
Case Else
.ColumnWidth = 12
End Select
.Borders.LineStyle = 1
.HorizontalAlignment = -4108
.VerticalAlignment = -4108
.WrapText = True
.Interior.Color = RGB(243, 244, 245)
.Font.Italic = True
End With
Next
objWrkSht.Range("A2").CopyFromRecordset rst
objWrkBk.SaveAs sPathToSave
If MsgBox("Закрыть Excel.Application?", _
vbYesNo + vbQuestion + vbDefaultButton2, "Закрытие") = vbYes Then
objWrkBk.Close
Else
objExcelApp.Visible = True
objExcelApp.WindowState = 3
objWrkBk.Activate
End If
ExportDataToExcel = sPathToSave
ExportDataToExcel_End:
On Error Resume Next
rst.Close
Set rst = Nothing
Set objWrkSht = Nothing
Set objWrkBk = Nothing
If sPathToSave = "" Then
objExcelApp.Quit
Set objExcelApp = Nothing
End If
Err.Clear
Exit Function
ExportDataToExcel_Err:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in Function ExportDataToExcel.", _
vbCritical, "Произошла ошибка!"
Err.Clear
Resume ExportDataToExcel_End
End Function
|
|