'要在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
1、定义新的Excel.Application对象(Dim EA as new Excel.Application)
2、新的Excel.Application隐藏(EA.Visible=False)
3、SET WB=EA.Workbook.open(”G:\1.xls”)'(WB事先定义成Wordbook对象:Dim WB as new workbook)
4、Var1=WB.Sheets(1).cells(2,2)
5、WB.Close False
6、SET EA=nothing
懂点vba的看了下面的步骤就懂了。
1、Dim Wb As Workbook
2、 Dim Temp As String
3、 Temp = ThisWorkbook.Path & "\xxxx.xls"
4、Set Wb = GetObject(Temp)
5、 Wb.Windows(1).Visible = False
6、Wb.Sheets(1).cells(1,1)="xxxxx"
7、Wb.Windows(1).Visible = True
8、Wb.SaveAs
Workbook.Open应该是Workbooks.Open