如何调用Excel文件?
我在VB6中的
References中 添加了
MS Excel9.0 Object Library
我如何使用它?
我想达到如下功能:
创建一个Excel文件,
在其上创建一个Sheet(名为Sheet1),
在Sheet1上的A2,B3单元格中写数据。
反过来,在一个已经存在的Excel文件中读取指定单元格(如B10)中数据。
问题点数:30、回复次数:2Top
1 楼edyang(化石)回复于 2000-11-11 20:04:00 得分 30
简单的例子:
Option Explicit
Private Sub Command1_Click()
Dim oExcelApp As Excel.Application
Dim oWorkbook As Excel.Workbook
Dim oWorksheet As Excel.Worksheet
Dim oCell As Excel.Range
Set oExcelApp = GetExcelApp()
If oExcelApp Is Nothing Then
Exit Sub
End If
oExcelApp.SheetsInNewWorkbook = 1
Set oWorkbook = oExcelApp.Workbooks.Add
Set oWorksheet = oWorkbook.Sheets(1)
If Not oWorksheet Is Nothing Then
Set oCell = oWorksheet.Range("A2")
oCell.Value = "ExcelAuto A2"
Set oCell = oWorksheet.Range("B3")
oCell.Value = "ExcelAuto B3"
Set oCell = oWorksheet.Range("B10")
oCell.Value = "ExcelAuto B10"
Else
MsgBox "Unexpected error", vbExclamation
End If
oWorkbook.SaveAs "c:\test.xls"
End Sub
Private Function GetExcelApp() As Excel.Application
Dim oExcelApp As Excel.Application
On Error Resume Next
Set oExcelApp = GetObject(, "Excel.Application")
If oExcelApp Is Nothing Then
Set oExcelApp = New Excel.Application
End If
If oExcelApp Is Nothing Then
MsgBox "You need to install Excel 2000 to run this example", vbInformation
Exit Function
End If
oExcelApp.Visible = True
Set GetExcelApp = oExcelApp
End Function
Private Sub Command2_Click()
Dim oExcelApp As Excel.Application
Dim oWorkbook As Excel.Workbook
Dim oWorksheet As Excel.Worksheet
Dim oCell As Excel.Range
Set oExcelApp = GetExcelApp()
If oExcelApp Is Nothing Then
Exit Sub
End If
Set oWorkbook = oExcelApp.Workbooks.Open("c:\test.xls")
Set oWorksheet = oWorkbook.Sheets(1)
If Not oWorksheet Is Nothing Then
Set oCell = oWorksheet.Range("B10")
MsgBox "Cell value in B10 is " & oCell.Value, vbInformation
Else
MsgBox "Unexpected error", vbExclamation
End If
End Sub
Top
2 楼bj_yangfang(泡泡)回复于 2001-05-30 13:47:00 得分 0
attention
Top




