大家?guī)臀铱纯?,下面這段程序為什么打印不了excel表格
首先建立一個窗體(FORM1)在窗體中加入一個DATA控件和一按鈕,
引用Microsoft Excel類型庫:
從"工程"菜單中選擇"引用"欄;
選擇Microsoft Excel 9.0 Object Library;
選擇"確定"。
然后在FORM的LOAD事件中加入:
Private Sub Form_Load()
’數(shù)據(jù)庫及表可以另選,本文以Nwind.mdb為例
Data1.DatabaseName = "C:\Program Files\Microsoft Visual Studio\VB98\Nwind.mdb"
Data1.RecordSource = "Customers"
Data1.Refresh
End Sub
在按鈕的CLICK事件中加入
Private Sub Command1_Click()
Dim Irow, Icol As Integer
Dim Irowcount, Icolcount As Integer
Dim Fieldlen() ’存字段長度值
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
With Data1.Recordset
.MoveLast
If .RecordCount < 1 Then
MsgBox ("Error 沒有記錄!")
Exit Sub
End If
Irowcount = .RecordCount ’記錄總數(shù)
Icolcount = .Fields.Count ’字段總數(shù)
ReDim Fieldlen(Icolcount)
.MoveFirst
For Irow = 1 To Irowcount + 1
For Icol = 1 To Icolcount
Select Case Irow
Case 1 ’在Excel中的第一行加標(biāo)題
xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1).Name
Case 2 ’將數(shù)組FIELDLEN()存為第一條記錄的字段長
If IsNull(.Fields(Icol - 1)) = True Then
Fieldlen(Icol) = LenB(.Fields(Icol - 1).Name)
’如果字段值為NULL,則將數(shù)組Filelen(Icol)的值設(shè)為標(biāo)題名的寬度
Else
Fieldlen(Icol) = LenB(.Fields(Icol - 1))
End If
xlSheet.Columns(Icol).ColumnWidth = Fieldlen(Icol)
’Excel列寬等于字段長
xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1)
’向Excel的CellS中寫入字段值
Case Else
Fieldlen1 = LenB(.Fields(Icol - 1))
If Fieldlen(Icol) < Fieldlen1 Then
xlSheet.Columns(Icol).ColumnWidth = Fieldlen1
’表格列寬等于較長字段長
Fieldlen(Icol) = Fieldlen1
’數(shù)組Fieldlen(Icol)中存放最大字段長度值
Else
xlSheet.Columns(Icol).ColumnWidth = Fieldlen(Icol)
End If
xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1)
End Select
Next
If Irow <> 1 Then
If Not .EOF Then .MoveNext
End If
Next
With xlSheet
.Range(.Cells(1, 1), .Cells(1, Icol - 1)).Font.Name = "黑體"
’設(shè)標(biāo)題為黑體字
.Range(.Cells(1, 1), .Cells(1, Icol - 1)).Font.Bold = True
’標(biāo)題字體加粗
.Range(.Cells(1, 1), .Cells(Irow, Icol - 1)).Borders.LineStyle = xlContinuous
’設(shè)表格邊框樣式
End With
xlApp.Visible = True ’顯示表格
xlBook.Save ’保存
Set xlApp = Nothing ’交還控制給Excel
End With
End Sub
作者:
llm9178 發(fā)表時間:2005-10-28 15:46:00
第1樓
我試過,增加如下一行即可:
Dim Fieldlen1
在保存后打?。?div style="height:15px;">
dim fieldlen1不定義也可以,我把最前點的要求定義語句去掉,printout函數(shù)是打印么?,我的意思是把系統(tǒng)數(shù)據(jù)庫的表格內(nèi)容顯示在excel里,打印都在excel里進行,這個功能實現(xiàn)的了么?