日前写了一段vb操作excel的代码,功能是向excel文件中填充数据,然后预览。
代码如下:
Public Enum enmPrintTag
csLintUnPrint = 0 'Not PrintPreview
csLintPrint = 1 'PrintPreview
End Enum
Public Sub FSubMakeReport01(ByVal pvstrFileName As String,
Optional ByVal pvenmPreview As enmPrintTag = csLintUnPrint)
Dim objExlApp As Object
Dim objExlBook As Object
Dim objExlSheet As Object
const csPstrExcelApp As String = "Excel.Application"
On Error GoTo SKipErrPos
Open the excel file
Set objExlApp = CreateObject(csPstrExcelApp)
Set objExlBook = objExlApp.Workbooks.Open(pvstrFileName)
objExlBook.Application.Visible = False
Set objExlSheet = objExlBook.Worksheets(1)
'Fill Data to Excel
If pvenmPreview = csLintPrint Then
objExlBook.Application.Visible = True
objExlBook.Save 'Save File
objExlBook.PrintPreview
Else
objExlBook.Save 'Save File
End If
objExlBook.PrintPreview
SkipEndPos:
On Error Resume Next
If Not objExlSheet Is Nothing Then
Set objExlSheet = Nothing
End If
If Not objExlBook Is Nothing Then
objExlBook.Saved = True
objExlBook.Close
Set objExlBook = Nothing
End If
If Not objExlApp Is Nothing Then
objExlApp.Quit
Set objExlApp = Nothing
End If
Exit Function
SKipErrPos:
......
End Sub
csLintUnPrint = 0 'Not PrintPreview
csLintPrint = 1 'PrintPreview
End Enum
Public Sub FSubMakeReport01(ByVal pvstrFileName As String,
Optional ByVal pvenmPreview As enmPrintTag = csLintUnPrint)
Dim objExlApp As Object
Dim objExlBook As Object
Dim objExlSheet As Object
const csPstrExcelApp As String = "Excel.Application"
On Error GoTo SKipErrPos
Open the excel file
Set objExlApp = CreateObject(csPstrExcelApp)
Set objExlBook = objExlApp.Workbooks.Open(pvstrFileName)
objExlBook.Application.Visible = False
Set objExlSheet = objExlBook.Worksheets(1)
'Fill Data to Excel
If pvenmPreview = csLintPrint Then
objExlBook.Application.Visible = True
objExlBook.Save 'Save File
objExlBook.PrintPreview
Else
objExlBook.Save 'Save File
End If
objExlBook.PrintPreview
SkipEndPos:
On Error Resume Next
If Not objExlSheet Is Nothing Then
Set objExlSheet = Nothing
End If
If Not objExlBook Is Nothing Then
objExlBook.Saved = True
objExlBook.Close
Set objExlBook = Nothing
End If
If Not objExlApp Is Nothing Then
objExlApp.Quit
Set objExlApp = Nothing
End If
Exit Function
SKipErrPos:
......
End Sub
上述代码在域内其他机器上都能够正常预览,当关闭预览的时候程序结束,但是在某台机器上偏偏预览窗口瞬间显示即消失。
我以为是程序bug,开始以为是因为objExlBook是一个局部变量,对象预览的时候马上执行后面的代码,这样对象马上消亡,当然就看到瞬间显示即消失的现象。但是预览的时候即程序中断执行,所以应该不是这个原因。
后来发现原来是那台机器没有装打印机,程序一点问题都没有。我绝倒!
艾,看来以后解决问题要从头分析起,不能动不动就主观臆断,导致时间的耗费。:-)