如何用VB or VBA 读取excel所有数据
取得excel文件所有内容:
'add microsoft ado frist.
Private Sub Command2_Click()
Dim adoConnection As New ADODB.Connection
Dim adoRecordset As New ADODB.Recordset
CommonDialog1.ShowOpen
'OLE DB + ODBC Driver 方式:
'adoConnection.Open "Data Provider=MSDASQL.1;driver=Microsoft Excel Driver (*.xls);DBQ=e:\temp\book2.xls"
'Microsoft.Jet.OLEDB.4.0 方式,(建?)
adoConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & CommonDialog1.FileName & ";Extended Properties='Excel 8.0;HDR=Yes'"
adoRecordset.Open "select * from [sheet1$]", adoConnection, adOpenKeyset, adLockOptimistic
Debug.Print adoRecordset.RecordCount
Dim i As Integer
Do Until adoRecordset.EOF
For i = 0 To adoRecordset.Fields.Count - 1
Debug.Print adoRecordset.Fields.Item(0).Name
Debug.Print adoRecordset.Fields.Item(0).Value
Next i
adoRecordset.MoveNext
Loop
End Sub
但还不知道如何取得sheet名,不好意思,那位老鸟知道请告知,谢谢
sheet名用Excel.Application对象
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open("C;\123.xls"))
For i = 1 To intSheetSum
strTemp=xlBook.Worksheets(i).name
Next i
Dim xlsconn As New ADODB.Connection
Dim xlscmd As New ADODB.Command
Dim rs As New ADODB.Recordset
xlsconn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\1.xls;Extended Properties=HTML EXPORT;Persist Security Info=False"
xlsconn.Open
Set rs = xlsconn.Execute("select * from [sheet1]")
set mshflexgrid.datasource=rs
rs.close
mshflexgrid.refresh
Dim xlsconn As New ADODB.Connection
Dim xlscmd As New ADODB.Command
Dim rs As New ADODB.Recordset
xlsconn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\1.xls;Extended Properties=excel 8.0;Persist Security Info=False"
xlsconn.Open
Set rs = xlsconn.Execute("select * from [sheet1]")
set mshflexgrid.datasource=rs
rs.close
mshflexgrid.refresh
(责任编辑:admin)