Dim xlApp As Excel.Application '定义EXCEL类 Dim xlBook As Excel.Workbook '定义工件簿类 Dim xlsheet As Excel.Worksheet '定义工作表类
Private Sub Command1_Click() '打开EXCEL过程 If Dir("D:\temp\excel.bz") = "" Then '判断EXCEL是否打开 Set xlApp = CreateObject("Excel.Application") '创建EXCEL应用类 xlApp.Visible = True '设置EXCEL可见 Set xlBook = xlApp.Workbooks.Open("D:\temp\bb.xls") '打开EXCEL工作簿 Set xlsheet = xlBook.Worksheets(1) '打开EXCEL工作表 xlsheet.Activate '激活工作表 xlsheet.Cells(1, 1) = "abc" '给单元格1行驶列赋值 xlBook.RunAutoMacros (xlAutoOpen) 运行EXCEL中的启动宏 Else MsgBox ("EXCEL已打开") End If End Sub
Private Sub Command2_Click() If Dir("D:\temp\excel.bz") <> "" Then '由VB关闭EXCEL xlBook.RunAutoMacros (xlAutoClose) '执行EXCEL关闭宏 xlBook.Close (True) '关闭EXCEL工作簿 xlApp.Quit '关闭EXCEL End If Set xlApp = Nothing '释放EXCEL对象 End End Sub