将数据插入表时,ADOB VBA Automation错误

时间:2018-07-25 17:07:17

标签: sql vba excel-2010 ado

我正在尝试在名为DataRange2 $的excel表中插入一行。来自同一个工作簿。我收到(运行时自动化错误-214721793)。当我查询诸如select * from DataRange2$之类的Excel工作簿时,我的代码有效。我想插入一行,但出现此错误。我正在使用ADOB,VBA和Excel 2010。

正在发送的SQL查询是:

SQL = "INSERT INTO [DataSheet2$] (Name, a, b, c, d, e) VALUES ('This is a name', 10, 20, 30, 40, 50)"
`Result` is the array which is populated with the returned rows 
runQuery SQL, result

代码:

Public Function runQuery(SQL As String, ByRef result() As String) As Integer
  Dim dataConection As New ADODB.connection
  Dim mrs As New ADODB.Recordset
  Dim DBPath As String
  Dim connectionString As String
  Dim size As Integer

  Set mrs = CreateObject("ADODB.Recordset")

  'Set cursor to start
  mrs.CursorLocation = adUseClient

  'Set database path
  DBPath = ThisWorkbook.FullName

  'You can provide the full path of your external file as shown below
  connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

  'Open connection to database
  dataConection.Open connectionString

  'Open record set (query or table, connection)
  mrs.Open SQL, dataConection

  'Record set returned update data
  If mrs.EOF Then
      runQuery = 0
      Exit Function
  Else
      runQuery = mrs.RecordCount
  End If

  'Populate array with result
  ReDim result(size) As String
  Dim i As Integer

  For i = 0 To (size - 1)
      result(i) = mrs!Name
      mrs.MoveNext
  Next i

  'Close record set and connection
  mrs.Close
  dataConection.Close
End Function

工作表标题如下

Name | a | b | c | d | e | Status | Action

1 个答案:

答案 0 :(得分:0)

尝试使用两个函数(1)插入新行,以及(2)获取x行的Names。这些需要两个单独的ADODB.Recordset。下面执行插入操作,但是无法通过Get

self