# 范例: vb6 连上Excel

Posted by 陈进富 on May 29, 1998 at 01:02:43:

In Reply to: 当然不对 posted by 小吴 on May 27, 1998 at 17:41:17:

以下是我的讲义中有关vb6 连上Excel
的范例，请注意xlApp,xlBook,xlSheet1的开启及关闭顺序

范例: vb6 连上Excel

Private Sub XlsTest()
Dim xlApp As EXCEL.Application ‘ 注意要先按装 Excel (建议使用Office97以上版本)
Dim xlBook As EXCEL.Workbook
Dim xlSheet1 As EXCEL.Worksheet
Dim SQL As String
Dim xlsFile As String
xlsFile = App.Path & "\test1.xls"
‘ 以下作法 即为 “ OLE Automation “
Set xlApp = CreateObject("EXCEL.APPLICATION")

' Set xlBook = xlApp.Workbooks.Add ‘ 新增
' Set xlSheet1 = xlApp.Sheets(1) ' 相同

Set xlBook = xlApp.Workbooks.Open(xlsFile) ‘ 开启已存在的XLS档
Set xlSheet1 = xlBook.Worksheets(1) ‘ 指定WorkSheet
xlApp.Visible = True ' 若不需显示Excel 画面 -->False
' 存资料至指定的位置 (列，行)
xlSheet1.Cells(1, 1).Value = "AA"
xlSheet1.Cells(1, 2).Value = "BB"
xlSheet1.Cells(1, 3).Value = "CC"

xlSheet1.Cells(2, 1).Value = 1
xlSheet1.Cells(2, 2).Value = 2
xlSheet1.Cells(2, 3).Value = 3
xlSheet1.Cells(3, 1).Value = 10
xlSheet1.Cells(3, 2).Value = 20
xlSheet1.Cells(3, 3).Value = 30
' Row, Col
On Error Resume Next

xlSheet1.Application.SaveWorkspace ' 储存Current WorkSheet

' xlSheet1.PrintPreview ' 可印前预视
' 可指定列印第N页到第X页
xlSheet1.PrintOut ' from page n ,to page n
xlApp.Quit ' ***** 使用完毕 一定要记得关闭Excel程式
' Release memory
Set xlSheet1 = Nothing
Set xlBook = Nothing
Set xlApp = Nothing

End Sub

Follow Ups: