|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
Public Sub ado方法导入EXCEL文件()
Dim lcConnectSring, szSQL, lcCommandText As String
Dim loADODBConnection As Variant
Dim loADODBRecordset As Variant
Dim fileToOpen
fileToOpen = Application.GetOpenFilename("打开所有文件,*.*")
If fileToOpen <> False Then
MsgBox "即将导入文件:" & fileToOpen & " 的内容!"
End If
' Dim fileToOpen As String
' Dim fdg As FileDialog
' Dim filename$
' Set fdg = Application.FileDialog(msoFileDialogOpen)
' With fdg
' .Filters.Clear
' .Filters.Add "EXCEL文件", "*.XLS"
' filename = .Show
' fileToOpen = fdg.SelectedItems(1)
' End With
lcConnectionString = "Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=" + fileToOpen + ";" & _
"ReadOnly=true"
lcCommandText = "select * from [1$]"
Set loADODBConnection = CreateObject("ADODB.Connection")
Set loADODBRecordset = CreateObject("ADODB.Recordset")
'打开变量,将loADODBConnection的内容装入loADODBRecordset
loADODBConnection.Open lcConnectionString
loADODBRecordset.Open lcCommandText, loADODBConnection, 3, 1, 1
Sheets("Sheet1").Activate
Dim r, f As Integer
r = 1
For f = 0 To loADODBRecordset.Fields.Count - 1
Sheets("Sheet1").Cells(r, f + 1).Value = loADODBRecordset.Fields(f).Name
Next
While Not loADODBRecordset.EOF
r = r + 1
For f = 0 To loADODBRecordset.Fields.Count - 1
Sheets("Sheet1").Cells(r, f + 1).Value = loADODBRecordset.Fields(f).Value
Next
loADODBRecordset.MoveNext
Wend
loADODBConnection.Close
Cells.Rows.AutoFit
Cells.Columns.AutoFit
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
End Sub |
|