【文章背景】
在VB系统中,通过添加“导出为Excel”按钮来实现将MSHFflexGrid表格中的数据导出到Excel表中,并由用户决定是否保存。
【如何实现】
在定义Excel对象之前要先引用Microsoft Excel 类型库,从“工程”菜单中选择“引用”,打开如图所示:
选择Microsoft Office 15.0 Object Library (Office 2013),确定即可。
找不到Microsoft Office 15.0 Object Library怎么办?
同样从“工程”菜单中选择“引用”,选择“浏览”,
C:\Program Files\Common Files\Microsoft Shared\OFFICE15\MSO.DLL,如图:
即可添加。
在模块中编写代码:
- '将MSHFlexGrid中数据导出到Excel
- Public Function ExportToExcel(myflexgrid As MSHFlexGrid)
- On eror GoTo ErrorMsg
- Dim xlApp As Object '申明Object类对象 后期绑定
- Dim xlBook As Object '
- Dim rows As Integer '总行数
- Dim cols As Integer '总列数
- Dim irow As Integer '
- Dim hcol As Integer '
- Dim icol As Integer '
- If myflexgrid.rows <= 1 Then '判断有无数据
- MsgBox "没有数据!",vbInformation,"提示"
- Exit Function
- Else
- Set xlApp = CreateObject("Excel.Application") '生成新的对象引用,引用Excel
- Set xlBook = xlApp.Workbooks.Add '创建空白的工作簿
- xlApp.Visible = True 'Excel可见
- With myflexgrid
- 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
- With xlApp
- .rows(1).Font.Bold = True '第一行为粗体
- .Cells.Select '选择整个工作表
- .Columns.AutoFit '自动调整列宽以适应文字
- .Cells(1,1).Select '
- End With
- xlApp.DisplayAlerts = False '关闭工作表,不提示用户保存
- Set xlApp = Nothing '释放xlApp对象
- Set xlBook = Nothing '释放xlBook对象
- Exit Function
- End If
- ErrorMsg:
- MsgBox "当前无法导出为Excel!",vbOKOnly + vbExclamation,"提示"
- End Function
在对应窗体中调用即可:
- '导出为Excel
- Private Sub Opcmdout_Click()
- Call ExportToExcel(myflexgrid)
- End Sub