vbでMSHFlexGridコントロールをExcelにエクスポート


vbプログラムでコントロールMSHFlexGridデータをEXCELテーブルにエクスポートし、データベースクエリのバックアップを実現します.
モジュール内の関数定義とリンクの作成
まず、関数の定義とリンク
'MSHFlexGrid Excel
Public Function ExportFlexDataToExcel(flex As MSHFlexGrid, g_CommonDialog As CommonDialog)
  
    On Error GoTo ErrHandler
    ' excel 
    Dim xlApp As Excel.Application
    Dim xlBook As Excel.Workbook
    Dim xlSheet As Excel.Worksheet
    
    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
                    
    Set xlApp = CreateObject("Excel.Application") ' excel 
    Set xlBook = xlApp.Workbooks.Add ' 
    xlApp.Visible = True

    With flex    ' MSHFlexGrid excel 
        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)
            Next iRow
            iCol = iCol + 1
        Next hCol
    End With

次に、関数にexcelのパーソナライズ設定を設定します.
 With xlApp         ' excel 
        .Rows(1).Font.Bold = True
        .Cells.Select
        .Columns.AutoFit
        .Cells(1, 1).Select
'        .Application.Visible = True
    End With
    
    xlBook.SaveAs (g_CommonDialog.FileName) ' excel 
    xlApp.Application.Visible = True
    xlApp.DisplayAlerts = True
その後、excelプログラムおよび関数のエラー処理を解放する
 'xlApp.Quit
    Set xlApp = Nothing  '" Excel excel 
    Set xlBook = Nothing
    flex.SetFocus
    MsgBox " Excel 。", vbInformation, " "
    Exit Function
                
ErrHandler:
    '  “ ” 
    If Err.Number <> 32755 Then
        MsgBox " !", vbCritical, " "
    End If
End Function

フォームで関数を呼び出す
Private Sub cmdToExcel_Click()
ExportFlexDataToExcel myflexgrid, cdlSelectExcel  'myflexgrid1 MSHFlexGrid   cdlSelectExcel commonDialog 
End Sub