VB中从MSFlexGrid记录导出为Excel

机房收费系统中多个窗体用到从MSFlexGrid记录导出为Excel,在VB要导出数据到Excel中,首先要在引用中添加Microsoft Excel 14.0 Object Library 引用,我的代码中用到了对话框,所以我添加了对话框CommonDialog控件。

由于机房收费系统中多次用到这个功能,我把这些代码写到了模块中,定义了一个公有的函数,具体代码如下所示:

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_Column 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
'获取表格中值,传递到Excel单元格中
          xlApp.Cells(iRow,iCol).Value = .TextMatrix(iRow - 1,hCol)

       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

' .Application.Visible = True

  End With

   ‘获取要保存文件的文件名,选择保存路径

  xlBook.SaveAs (g_CommonDialog.FileName)

  xlApp.Application.Visible = True

  xlApp.DisplayAlerts = False

  Set xlApp = Nothing '"交还控制给Excel

  Set xlBook = Nothing

  MsgBox "数据已经导出到Excel中。","成功"

 Exit Function
    

ErrHandler:

  ' 用户按了“取消”按钮
  If Err.Number <> 32755 Then
  MsgBox "数据导出失败!",vbCritical,"警告"
  End If
End Function
 

定义好公有函数之后,我们就可以在窗体中多次调用它,格式为:

    Call ExportFlexDataToExcel  MSFlexGrid,CommonDialog

其中MSFlexGridMSFlexGrid的名字,CommonDialog为对话框名。

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...