我想用VB调用EXCEL里面的数据

2024-11-18 12:37:17
推荐回答(2个)
回答(1):

1、打开VB-》在form1上增加一个command1按钮,双击command1按钮,把以下代码放入窗体内;
2、运行前,在菜单的选“工程”->“引用”->找到Microsoft Excel 12.0 Object Library->确定;然后才可以运行;
3、代码如下:
Dim ExApp As New Excel.Application
Dim Exb As Excel.Workbook
Dim Exsh As Excel.Worksheet
Dim arr(6, 6) As Integer '定义一个二维数组,数据类型为整数
ExApp.Workbooks.Open "c:\book1.xls" '打开EXEL文件,路径和文件名自己根据实际修改
Set Exb = ExApp.Workbooks(1)
Set Exsh = Exb.Worksheets("Sheet1")
For i = 1 To 6 '假设是读取A1:F6的6X6区域数据
For j = 1 To 6
arr(i, j) = Exsh.Cells(i, j)
Next j
Next i
'把自己需要对数组数据进一步处理的部分加进去...
ExApp.Workbooks.Close
ExApp.Quit
Set ExApp = Nothing

回答(2):

首先引用Microsoft Excel Object Library,然后:
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Dim OpenExecl As Long
Dim ExcelPath As String

Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
Set xlBook = xlApp.Workbooks.Open(App.Path + "\abc.xls") '打开存在的execl文件
xlApp.Visible = true '设置EXCEL对象可见(或不可见)
'Set xlBook = xlApp.Workbooks.Add() '打开新建立的EXCEL工件簿文件
Set xlSheet = xlBook.Worksheets("Sheet1") '设置活动工作表

ExcelPath = xlApp.Path 'execl.exe的路径

然后,xlSheet.Cells(1, 1)就是指代左上角的单元格了.可以对它读写了.xlSheet.Cells(2, 1) ....可以指定相应的单元格.