Private Sub Command1_Click()
Dim xlApp as Object
Dim wb as Object
Set xlApp = CreateObject("Excel.Application") '创建Excel环境
Set wb = xlApp.WorkBooks.Open("C:\xx.xls") '打开指定路径下的工作簿
wb.Sheets(1).Cells(1,"A").Value = Text1.Text
'向xx.xls工作簿的Sheets(1)第一张工作表的A1单元格写入Text1文本框里面的.Text。
Dim i As Long
For i = 1 to 10 '用一个循环向B1,B2,...,B10单元格里面写入 i*2 偶数。
wb.Sheets(1).Cells(i,"B") = i * 2
Next
wb.Close True '关闭xx.xls
xlApp.Quit '退出Excel环境
Msgbox "写入完成,请到C:\下查看xx.xls文件。"
End Sub
以上是用VB操作工作簿最简单的代码。
用FlexGrid类似控件输出查询excel结果,修改数据后保存到excel,同时重新读取excel数据到控件,我个人比较熟悉这样的操作方式,一般不直接引用excel对象。
读取excel的代码:
Dim objExcelFile As Excel.Application
Dim objImportSheet As Excel.Worksheet
Dim objWorkBook As Excel.Workbook
Set objExcelFile = New Excel.Application '´´创建新的excel应用程序
objExcelFile.DisplayAlerts = False 'Excel不可见
Set objWorkBook = objExcelFile.Workbooks.Open(App.Path & "\公司在册人员名单.xls")
Set objImportSheet = objWorkBook.Sheets(1) '选定工作表单1
objWorkBook.RunAutoMacros (xlAutoOpen)
Do Until line = 3000
line = line + 1
a(line)= objImportSheet.Cells(line, 2)
b(line)= objImportSheet.Cells(line, 3)
Loop
objWorkBook.RunAutoMacros (xlAutoClose) '''后台关闭excel
objWorkBook.Close (True)
objExcelFile.Quit
保存excel数据的代码:
Dim objExcelFile As Excel.Application
Dim objImportSheet As Excel.Worksheet
Dim objWorkBook As Excel.Workbook
Set objExcelFile = New Excel.Application
objExcelFile.DisplayAlerts = False
Set objWorkBook = objExcelFile.Workbooks.Open(App.Path & "\公司在册人员.xls")
Set objImportSheet = objWorkBook.Sheets(1)
objWorkBook.RunAutoMacros (xlAutoOpen)
objImportSheet.Cells(PrizeLine, 7) = a
objImportSheet.Cells(PrizeLine, 8) = b
objImportSheet.Cells(PrizeLine, 9) =c
objExcelFile.SaveWorkspace '''保存表单
objWorkBook.RunAutoMacros (xlAutoClose)
objWorkBook.Close (True)
objExcelFile.Quit