通过vba将MDB表导入EXCEL - 需要字段名称/标题

时间:2017-01-25 15:04:18

标签: excel vba excel-vba import ms-access-2010

我在网上找到了一些将访问记录导入excel的代码。 strFilePath是MDB的文件路径,strTableName是我要导入的表名

Sub importAccessdata()

Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sQRY As String
Dim strFilePath As String

strFilePath = Sheets("Setup").Range("C2").Value
strTableName = Sheets("Setup").Range("C4").Value

Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFilePath & ";"

sQRY = "SELECT * FROM " & strTableName & ""

rs.CursorLocation = adUseClient
rs.Open sQRY, cnn, adOpenStatic, adLockReadOnly

Application.ScreenUpdating = False
Sheet3.Range("A1").CopyFromRecordset rs

rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub

End Sub

所有记录导入速度非常快,但我无法获取字段名称以填充它们!我可以做一个简单的修改来携带数据的字段名称吗?

1 个答案:

答案 0 :(得分:1)

这就是我使用的 -

Private Sub PullSummaryData()
Const strDb As String = "C:\db\AccessDatabase.accdb"
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim i As Integer

Sheets("Summary").Select

  Const strQry As String = "SELECT * FROM [AccessDataTable]"

  Set cn = New ADODB.Connection
  cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDb & ";"

  Set rs = New ADODB.Recordset

  With rs
    Set .ActiveConnection = cn
    .Open strQry
  End With

With Sheets("Summary")
  For i = 1 To rs.Fields.Count
    .Cells(2,i).Value = rs.Fields(i-1).Name  'fields is a 0 based collection
  Next i
  .Range("A3").CopyFromRecordset rs
End With

  rs.Close
  cn.Close
End Sub