##前言
#####机房系统中有好几个窗体都需要把查询的信息导出Excel,那么,既然都一样,是不是就可以写出一个代码再复制粘贴就OK了。代码中只要有大量重复的代码出现就代表有很大的冗余,而我们为了让程序更快速运行,代码量更少,就可以使用函数,使用时候进行调用就可以了。我们来看看是如何使用代码实现这个功能的!
打开工程—引用—选择Microsoft Ofiice 15.0 Object Library.(我的excel是2013版,不同的版本对应的版本号不同。)
工程—部件—选择Microsoft Windows Common Controls 6.0
在窗体中添加CommonDiaLog控件,在模块中编写导出Excel代码。
Public Function ExportFlexDataToExcel(flex As MSFlexGrid, g_CommonDialog As CommonDialog)
On Error GoTo ErrHandler
Dim xlApp As Object
Dim xlBook As Object
Dim Rows As Integer, Cols As Integer
Dim iRow As Integer, hCol As Integer, iCol As Integer
Dim New_Col As Boolean
Dim New_Colum As Boolean
g_CommonDialog.CancelError = True
On Error GoTo ErrHandler
g_CommonDialog.Flags = cdlOFNHideReadOnly ' 设置标志
g_CommonDialog.Filter = " All Files (*.*)|*.*|Excel Files" & _
"(*.xls)|*.xls|Batch Files (*.bat)|*.bat " ' 设置过滤器
g_CommonDialog.FilterIndex = 2 ' 指定缺省的过滤器
g_CommonDialog.ShowSave '显示"打开"对话框
If flex.Rows <= 1 Then '判断表格中是否有数据
MsgBox "没有数据!", vbInformation, "警告"
Exit Function
End If
'打开Excel ,添加工作簿
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
xlApp.Visible = False
'遍历表格中的记录,传递到Excel中
With flex
Rows = .Rows
Cols = .Cols
iRow = 0
iCol = 1
For hCol = 0 To Cols - 1
For iRow = 1 To Rows
xlApp.Cells(iRow, iCol).Value = .TextMatrix(iRow - 1, hCol) '获取表格中值,传递到Excel单元格中
Next iRow
iCol = iCol + 1
Next hCol
End With
'设置Excel的属性
With xlApp
.Rows(1).Font.Bold = True
.Cells.Select
.Columns.AutoFit
.Cells(1, 1).Select
End With
'获取要保存文件的文件名,选择保存路径
xlBook.SaveAs (g_CommonDialog.FileName)
xlApp.Application.Visible = True
xlApp.DisplayAlerts = False
'交还控制给Excel
Set xlApp = Nothing
Set xlBook = Nothing
MsgBox "数据已经导出到Excel!", vbInformation, "成功"
Exit Function
ErrHandler:
'用户按了“取消”按钮
If Err.Number <> 32755 Then
MsgBox "数据导出失败!", vbCritical, "警告"
End If
End Function
才窗体中使用调用语句
'MSFlexGrid, CommonDialog分别为控件名
Call ExportFlexDataToExcel(MSFlexGrid, CommonDialog)
##结语
#####看起来不容易实现的功能,当我们学会了就会发现没什么难的。向下个困难冲鸭!