'要在VB中操作Excel,需要引用Excel对象模型
'方法,在菜单里选择[工程] -- [引用],在窗口里勾选 Microsoft Excel XX.X Object Library
'其中,XX.X取决于你安装的Office的版本号
Private Sub Command6_Click()
Dim excel_App As Excel.Application
Dim excel_Book As Excel.Workbook
Dim excel_sheet As Excel.Worksheet
'启动Excel
Set excel_App = CreateObject("Excel.Application") '引用程序对象实例
excel_App.Visible = False '设置Excel为不可见
'打开文件
Set excel_Book = excel_App.Workbooks.Open("G:\1.XLS") '工作簿实例
Set excel_sheet = excel_Book.Worksheets("Sheet2") '数据表实例
excel_sheet.Range("C1").Value = "你好!" '设置单元格C1的值为"你好!"
excel_sheet.Range("A1").Value = 100 '设置单元格A1的值为100
excel_sheet.Range("A2").Value = 9 '设置单元格A2的值为9
excel_sheet.Range("A3").Value = excel_sheet.Range("A1").Value + excel_sheet.Range("A2").Value '计算
'''''''''''''''''''''''''''''''''''
'读取数据到变量
x = excel_sheet.Range("A2").Value ' 把单元格"A2"里的数据读取出来
'关闭Excel文件,注意下面步骤很重要,不能少!!!
Set excel_sheet = Nothing
excel_App.ActiveWorkbook.Close savechanges:=True '保存对EXCELL进行更改。
Set excel_Book = Nothing
excel_App.Quit
Set excel_App = Nothing