【VB】MSHFlexGrid表格数据导出到Excel

前端之家收集整理的这篇文章主要介绍了【VB】MSHFlexGrid表格数据导出到Excel前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

文章背景】


在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,如图:


即可添加


在模块中编写代码

  1. '将MSHFlexGrid中数据导出到Excel
  2. Public Function ExportToExcel(myflexgrid As MSHFlexGrid)
  3. On eror GoTo ErrorMsg
  4. Dim xlApp As Object '申明Object类对象 后期绑定
  5. Dim xlBook As Object '
  6. Dim rows As Integer '总行数
  7. Dim cols As Integer '总列数
  8. Dim irow As Integer '
  9. Dim hcol As Integer '
  10. Dim icol As Integer '
  11. If myflexgrid.rows <= 1 Then '判断有无数据
  12. MsgBox "没有数据!",vbInformation,"提示"
  13. Exit Function
  14. Else
  15. Set xlApp = CreateObject("Excel.Application") '生成新的对象引用,引用Excel
  16. Set xlBook = xlApp.Workbooks.Add '创建空白的工作簿
  17. xlApp.Visible = True 'Excel可见
  18. With myflexgrid
  19. rows = .rows
  20. cols = .cols
  21. irow = 0
  22. icol = 1
  23. For hcol = 0 To cols - 1 '列循环
  24. For irow = 1 To rows '行循环
  25. xlApp.Cells(irow,icol).Value = .TextMatrix(irow - 1,hcol) '将表中数据送到Excel
  26. Next irow
  27. icol = icol + 1
  28. Next hcol
  29. End With
  30. With xlApp
  31. .rows(1).Font.Bold = True '第一行为粗体
  32. .Cells.Select '选择整个工作表
  33. .Columns.AutoFit '自动调整列宽以适应文字
  34. .Cells(1,1).Select '
  35. End With
  36. xlApp.DisplayAlerts = False '关闭工作表,不提示用户保存
  37. Set xlApp = Nothing '释放xlApp对象
  38. Set xlBook = Nothing '释放xlBook对象
  39. Exit Function
  40. End If
  41. ErrorMsg:
  42. MsgBox "当前无法导出为Excel!",vbOKOnly + vbExclamation,"提示"
  43. End Function

在对应窗体中调用即可:

  1. '导出为Excel
  2. Private Sub Opcmdout_Click()
  3. Call ExportToExcel(myflexgrid)
  4. End Sub

猜你在找的VB相关文章