从"工程"菜单中选择"引用"栏;选择Microsoft Excel 14 .0 Object Library,然后选择"确定"。表示在工程中要引用EXCEL类型库。
然后就是实现从MSHFlexGrid控件中将数据导出到EXCEL表中(注意:MSHFlexGrid控件是从第0行,第0列开始的,而EXCEL却是从第1行,第1列开始的)。代码如下:
- Dim i As Long Dim j As Long
- If myFlexGrid.TextMatrix(1,0) = "" Then
- MsgBox "没有数据导出",vbInformation,"提示"
- Exit Sub
- End If
- '创建一个Application对象
- Dim excelApp As Excel.Application
- Set excelApp = New Excel.Application
- '绑定
- Set excelApp = CreateObject("Excel.Application")
- '向Excel中写入数据
- Dim exbook As Excel.Workbook
- Dim exsheet As Excel.Worksheet
- Set exbook = excelApp.Workbooks.Add
- excelApp.SheetsInNewWorkbook = 1
- '设置为可见
- excelApp.Visible = True
- '将控件MSHFlexGrid显示的内容写入Excel中
- With excelApp.ActiveSheet
- For i = 1 To myFlexGrid.Rows
- For j = 1 To myFlexGrid.Cols
- .Cells(i,j).Value = "" & Format$(myFlexGrid.TextMatrix(i - 1,j - 1))
- Next j
- Next i
- End With
- '清空并关闭
- Set exsheet = Nothing
- Set exbook = Nothing
- Set excelApp = Nothing
以上只是用到EXCEL与VB交互的最基本的内容,下面我们来做一些扩展:
首先创建 Excel 对象,使用ComObj:
DimexcelApp as Excel.Application
SetexcelApp as new Excel.Application
1)显示当前窗口:
excelApp.Visible= True
2)更改 Excel 标题栏:
excelApp.Caption='学生上机记录';
3)添加新工作簿:
excelApp.WorkBooks.Add;
4)打开已存在的工作簿:
EexcelApp.WorkBooks.Open('CExcelDemo.xls' );
5)设置第2个工作表为活动工作表:
excelApp.WorkSheets(2).Activate;
或 excelApp.WorkSheets( 'Sheet2').Activate;
6)给单元格赋值:
excelApp.Cells(1,4).Value= '第一行,第四列';
12)清除第一行第四列单元格公式:
excelApp.ActiveSheet.Cells(1,4).ClearContents;
13)设置第一行字体属性:
excelApp.ActiveSheet.Rows(1).Font.Name= '隶书';
excelApp.ActiveSheet.Rows(1).Font.Color= clBlue;
excelApp.ActiveSheet.Rows(1).Font.Bold= True;
excelApp.ActiveSheet.Rows(1).Font.UnderLine= True;
k.打印单元格网线:
excelApp.ActiveSheet.PageSetup.PrintGridLines= True;
15)拷贝操作:
a.拷贝整个工作表:
excelApp.ActiveSheet.Used.Range.Copy;
b.拷贝指定区域:
excelApp.ActiveSheet.Range('A1E2' ).Copy;
c.从A1位置开始粘贴:
excelApp.ActiveSheet.Range.('A1' ).PasteSpecial;
d.从文件尾部开始粘贴:
excelApp.ActiveSheet.Range.PasteSpecial;
16)插入一行或一列:
a.excelApp.ActiveSheet.Rows(2).Insert;
b.excelApp.ActiveSheet.Columns(1).Insert;
17)删除一行或一列:
a.excelApp.ActiveSheet.Rows(2).Delete;
b.excelApp.ActiveSheet.Columns(1).Delete;
18)打印预览工作表:
excelApp.ActiveSheet.PrintPreview;
19)打印输出工作表:
excelApp.ActiveSheet.PrintOut;
20)工作表保存:
If notexcelApp.ActiveWorkBook.Saved then
excelApp.ActiveSheet.PrintPreview
End if
21)工作表另存为:
excelApp.SaveAs('CExcelDemo1.xls' );
22)放弃存盘:
excelApp.ActiveWorkBook.Saved= True;
23)关闭工作簿:
excelApp.WorkBooks.Close;
24)退出 Excel:
excelApp.Quit;
25)设置工作表密码
excelApp.ActiveSheet.Protect"123",DrawingObjects=True,Contents=True,Scenarios=True
26)EXCEL的显示方式为最大化
excelApp.Application.WindowState= xlMaximized
27)工作薄显示方式为最大化
excelApp.ActiveWindow.WindowState= xlMaximized
28)设置打开默认工作薄数量
excelApp.SheetsInNewWorkbook= 3
29)'关闭时是否提示保存(true 保存;false 不保存)
excelApp.DisplayAlerts= False