Private Sub Print_Click()
Dim xlapp As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Dim i, j As Integer
Dim WT As New clsWaitableTimer    Set xlapp = CreateObject("excel.application")
    Set xlbook = xlapp.Workbooks.Add
    Set xlsheet = xlbook.Worksheets(1)
    'On Error GoTo cls
    xlsheet.Name = "数据记录"
    xlsheet.Columns(1).ColumnWidth = 10
    xlsheet.Columns(3).ColumnWidth = 6
    xlsheet.Columns(4).ColumnWidth = 8
    xlsheet.Columns(5).ColumnWidth = 8
    xlsheet.Columns(9).ColumnWidth = 6
    xlapp.Range("A1:I1").Merge
    xlapp.Range("A1").Select
    With Selection
        .HorizontalAlignment = xlCenter
    End With
    With Selection.Font
        .Size = 20
        .Bold = True
    End With
    With xlsheet.PageSetup
        .PrintTitleRows = "A2:I2"
    End With
    xlsheet.Cells(1, 1) = "数据报告"
    For i = 0 To MSFlexGrid1.Rows - 1
        For j = 0 To MSFlexGrid1.Cols - 1
            xlsheet.Cells(i + 2, j + 1) = MSFlexGrid1.TextMatrix(i, j)
        Next j
    Next i
    xlsheet.PageSetup.PrintGridlines = True
    xlsheet.Cells.Borders.LineStyle = xlContinuous
    xlapp.Visible = True
    xlsheet.PrintPreview
    xlapp.DisplayAlerts = False
    xlbook.Close False
    Set xlbook = Nothing
    xlapp.Quit
    Set xlapp = Nothing
End Sub
程序运行后,此段代码第一次执行没有错误,但再次被执行时报错,在.HorizontalAlignment = xlCenter这报错,实时错误'91'对象变量或With块变量未设置,那位大侠帮忙解决一下啊 感激不尽

解决方案 »

  1.   

    Private Sub Print_Click()
    Dim xlapp As Excel.Application
    Dim xlbook As Excel.Workbook
    Dim xlsheet As Excel.Worksheet
    Dim i, j As Integer
    Dim WT As New clsWaitableTimer    Set xlapp = CreateObject("excel.application")
        Set xlbook = xlapp.Workbooks.Add
        Set xlsheet = xlbook.Worksheets(1)
        'On Error GoTo cls
        xlsheet.Name = "数据记录"
        xlsheet.Columns(1).ColumnWidth = 10
        xlsheet.Columns(3).ColumnWidth = 6
        xlsheet.Columns(4).ColumnWidth = 8
        xlsheet.Columns(5).ColumnWidth = 8
        xlsheet.Columns(9).ColumnWidth = 6
        xlapp.Range("A1:I1").Merge
        xlapp.Range("A1").Select
        
            xlapp.Cells.HorizontalAlignment = xlCenter
            xlapp.Selection.Font.Size = 20
            xlapp.Selection.Font.Bold = True
            xlsheet.PageSetup.PrintTitleRows = "A2:I2"    xlsheet.Cells(1, 1) = "数据报告"
        For i = 0 To MSFlexGrid1.Rows - 1
            For j = 0 To MSFlexGrid1.Cols - 1
                xlsheet.Cells(i + 2, j + 1) = MSFlexGrid1.TextMatrix(i, j)
            Next j
        Next i
        xlsheet.PageSetup.PrintGridlines = True
        xlsheet.Cells.Borders.LineStyle = xlContinuous
        xlapp.Visible = True
        xlsheet.PrintPreview
        xlapp.DisplayAlerts = False
        xlbook.Close False
        Set xlbook = Nothing
        xlapp.Quit
        Set xlapp = Nothing
    End Sub