如何将表名传递给VBA中的sql查询

时间:2014-08-27 08:24:33

标签: sql excel vba excel-vba ms-access

我正在使用以下代码将表从MDB数据库加载到Excel工作表。我正在尝试将表名定义为变量并将其传递给查询但我收到的错误与下面的代码。我怎样才能在VBA

中执行此操作
Public Sub ReadMdb()

  Dim cn As Object, rs As Object
  Dim intColIndex As Integer
  Dim DBFullName As String
  Dim TargetRange As Range

  DBFullName = Application.GetOpenFilename()

  On Error GoTo Oops

  Application.ScreenUpdating = False

  Set TargetRange = Sheets("Sheet1").Range("A1")

  Set cn = CreateObject("ADODB.Connection")
  cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DBFullName
  Set rs = CreateObject("ADODB.Recordset")

  Dim tableName As String
  tableName = "Students"

  rs.Open "SELECT * FROM tableName", cn, , , adCmdText


  ' Write the field names
  For intColIndex = 0 To rs.Fields.Count - 1
    TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
  Next

  ' Write recordset
  TargetRange.Offset(1, 0).CopyFromRecordset rs

LetsContinue:
  Application.ScreenUpdating = True
  On Error Resume Next
  rs.Close
  Set rs = Nothing
  cn.Close
  Set cn = Nothing
  On Error GoTo 0
  Exit Sub
Oops:
  MsgBox "Error Description :" & Err.Description & vbCrLf & _
        "Error at line     :" & Erl & vbCrLf & _
        "Error Number      :" & Err.Number
  Resume LetsContinue


End Sub

2 个答案:

答案 0 :(得分:6)

您可以将表名插入SQL:

rs.Open "SELECT * FROM [" & tableName & "]", cn, , , adCmdText

答案 1 :(得分:2)

考虑到您返回所有行和所有列,您可以使用命令类型adCmdTable,然后您不需要任何SQL,只需命名您想要的表。