思路:
1.取得excel对象,然后控制该对象,读取该对象的所有工作表,并写入listbox,
2.当在用户listbox选取某一工作表时,用ADODC控件连接excel,再把DataGrid绑定ADODC控件,通过DataGrid显示表内的数据
*详细方法如下*
建一个窗体:
增加listbox,dataGrid,adodc 控件各1个
窗体内代码如下
Option Explicit
Public path As String 'excel文件路径
Private Sub Form_Load()
Dim myexcel As New Excel.Application
Dim mybook As Workbook
Dim mysheet As Worksheet
Dim su, j As Long
'excel表路径
path = "D:\我的文档\3000条新书无资料11_3.xls"
Set mybook = myexcel.Workbooks.Open(path)
'遍历每个工作表,取出所有表名
Dim a As Worksheet
For Each a In mybook.Sheets '在此循环里,你可以添加到listbox控件
List1.AddItem a.Name
' MsgBox a.Name '显示工作表的名称
' MsgBox a.Range("a1") '显示A1单元格
Next
mybook.Close
Set mysheet = Nothing
Set mybook = Nothing
Set myexcel = Nothing
End Sub
Sub List1_Click()
'单击listbox的表名时
Dim Conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim Sql As String, strSheetName As String
strSheetName = List1.Text
Sql = "select * from [" & strSheetName & "$]" '指定EXCEL表
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & path & ";Extended Properties='Excel 8.0;HDR=Yes'" '连接EXCEL文件
Adodc1.RecordSource = Sql
Set DataGrid1.DataSource = Adodc1
Adodc1.Refresh
End Sub
温馨提示:答案为网友推荐,仅供参考