【VB Excel】VB 操作Excel基本步骤
VB操作EXCEL,实现数据读取
1、定义Excel操作变量 |
Dim objExcelFile As Excel.Application Dim objWorkBook As Excel.Workbook Dim objImportSheet As Excel.Worksheet |
2、打开Excel进程,并打开目标Excel文件 |
Set objExcelFile = New Excel.Application objExcelFile.DisplayAlerts = False Set objWorkBook = objExcelFile.Workbooks.Open(strFileName) Set objImportSheet = objWorkBook.Sheets(1) |
3、获取Excel有效区域的行和列数 |
intLastColNum = objImportSheet.UsedRange.Columns.Count intLastRowNum = objImportSheet.UsedRange.Rows.Count |
4、逐行读取Excel中数据 |
由于前两行为Header部分,所以需要从第三行读取 如果第1到第10个单元格的值均为空或空格,则视为空行 For intCountI = 3 To intLastRowNum ''Check if Empty Data Row blnNullRow = True For intI = 1 To 10 If Trim$(objImportSheet.Cells(intCountI, intI).Value) <> "" Then blnNullRow = False End If Next intI 若不是空行,则进行读取动作,否则继续向后遍历Excel中的行 If blnNullRow = False Then 获取单元格中的数据,做有效性Check,并将合法数据创建为实体存入对象数组中 objImportSheet.Cells(intCountI, 1).Value …… End If Next intCountI |
5、退出Excel进程,并关闭Excel相关操作对象 |
objExcelFile.Quit Set objWorkBook = Nothing Set objImportSheet = Nothing Set objExcelFile = Nothing |
Private Sub Command3_Click()
Dim i As Long
Dim j As Long
Dim objExl As Excel.Application '声明对象变量
Me.MousePointer = 11 '改变鼠标样式
Set objExl = New Excel.Application '初始化对象变量
objExl.SheetsInNewWorkbook = 1 '将新建的工作薄数量设为1
objExl.Workbooks.Add '增加一个工作薄
objExl.Sheets(objExl.Sheets.Count).Name = "book1" '修改工作薄名称
objExl.Sheets.Add , objExl.Sheets("book1") '增加第二个工作薄在第一个之后
objExl.Sheets(objExl.Sheets.Count).Name = "book2"
objExl.Sheets.Add , objExl.Sheets("book2") '增加第三个工作薄在第二个之后
objExl.Sheets(objExl.Sheets.Count).Name = "book3"
objExl.Sheets("book1").Select '选中工作薄<book1>
For i = 1 To 50 '循环写入数据
For j = 1 To 5
If i = 1 Then
objExl.Selection.NumberFormatLocal = "@" '设置格式为文本
objExl.Cells(i, j) = " E " & i & j
Else
objExl.Cells(i, j) = i & j
End If
Next
Next
objExl.Rows("1:1").Select '选中第一行
objExl.Selection.Font.Bold = True '设为粗体
objExl.Selection.Font.Size = 24 '设置字体大小
objExl.Cells.EntireColumn.AutoFit '自动调整列宽
objExl.ActiveWindow.SplitRow = 1 '拆分第一行
objExl.ActiveWindow.SplitColumn = 0 '拆分列
objExl.ActiveWindow.FreezePanes = True '固定拆分
objExl.ActiveSheet.PageSetup.PrintTitleRows = "$1:$1" '设置打印固定行
objExl.ActiveSheet.PageSetup.PrintTitleColumns = "" '打印标题
objExl.ActiveSheet.PageSetup.RightFooter = "打印时间: " & _
Format(Now, "yyyy年mm月dd日 hh:MM:ss")
objExl.ActiveWindow.View = xlPageBreakPreview '设置显示方式
objExl.ActiveWindow.Zoom = 100 '设置显示大小
'给工作表加密码
objExl.ActiveSheet.Protect "123", DrawingObjects:=True, _
Contents:=True, Scenarios:=True
objExl.Application.IgnoreRemoteRequests = False
objExl.Visible = True '使EXCEL可见
objExl.Application.WindowState = xlMaximized 'EXCEL的显示方式为最大化
objExl.ActiveWindow.WindowState = xlMaximized '工作薄显示方式为最大化
objExl.SheetsInNewWorkbook = 3 '将默认新工作薄数量改回3个
Set objExl = Nothing '清除对象
Me.MousePointer = 0 '修改鼠标
Exit Sub
End Sub