提问人:Hunter Garrison 提问时间:11/2/2023 更新时间:11/2/2023 访问量:83
如何使用 vba 将 Excel 中的数据列插入到 Access 数据库的字段中
How to insert columns of data from Excel into fields of an Access database using vba
问:
我正在尝试在Excel中编写VBA代码,该代码将Excel工作表的列插入Access数据库的字段中。我正在尝试将列“NDC11”、“ProductNameLong”和“ProductName2”插入到我的 Access 数据库的字段中,这些字段分别命名为“NDC11”、“ProductNameLong”和“ProductName2”。这是我目前拥有的代码。
Sub DataPuller()
Dim refresh
Dim year As String
Dim intColIndex As Integer
Dim strPath As String
Dim strProv As String
Dim strConn As String
Dim Conn As New Connection
Dim rsQry As New Recordset
Dim strQry As String
Dim NDCs As Range
Dim ProductName2s As Range
refresh = MsgBox("Start New Query?", vbYesNo)
If refresh = vbYes Then
year = Application.InputBox("Which year would you like CMS Utilization Data from:" & vbNewLine & "2019, 2020, 2021, or 2022?", "Input Year")
If year = "2022" Then
On Error GoTo Whoa
strPath = "C:\Users\hgarrison\Documents\PRM DOCS\1Q2022 - 4Q2022 CMS Utilization Database.accdb"
strProv = "Microsoft.ACE.OLEDB.12.0;"
strConn = "Provider=" & strProv & "Data Source=" & strPath
Conn.Open strConn
strQry = "DELETE * from MB_without_financials"
Conn.Execute strQry
Sheets.Add.Name = "Data"
xlFilepath = Application.ThisWorkbook.FullName
strQry = "INSERT INTO MB_without_financials(NDC11, ProductNameLong, ProductName2) SELECT NDC11, ProductNameLong, ProductName2 FROM [Excel 12.0 xml;HDR=YES;DATABASE=" & xlFilepath & "].[Sheet1$]"
Conn.Execute strQry
LetsContinue:
Application.ScreenUpdating = True
On Error Resume Next
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
On Error GoTo 0
Exit Sub
Whoa:
MsgBox "Error Description :" & Err.Description & vbCrLf & _
"Error at line :" & Erl & vbCrLf & _
"Error Number :" & Err.Number
Resume LetsContinue
End If
End If
End Sub
我的问题是在“INSERT”SQL查询上。我收到错误,说“没有为一个或多个必需参数提供值”。如何将 excel 中的这些列插入到这些特定的 Access 字段中?任何帮助将不胜感激。
答:
1赞
CDP1802
11/2/2023
#1
试试这个简短的测试程序来确认字段名称
Sub mydebug()
Dim conn As Connection, rs As ADODB.Recordset
Dim sql As String, i As Long, msg As String
Set conn = New ADODB.Connection
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=Database2.accdb"
.Open
sql = "SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & Application.ThisWorkbook.FullName & "].[Sheet1$]"
Debug.Print sql
Set rs = conn.Execute(sql)
For i = 1 To rs.Fields.Count
msg = msg & vbLf & i & " [" & rs.Fields(i - 1).Name & "]"
Next
MsgBox "Field Names" & msg, vbInformation
End With
End Sub
0赞
Hunter Garrison
11/2/2023
#2
我弄清楚了我的问题......这很尴尬,但有些人将来可能会面对它。我的问题是我正在PERSONAL中编码VBA代码。XLSB 和我打电话给以下人员:
xlFilePath = Application.ThisWorkbook.FullName
相反,我应该使用:
xlFilePath = Application.ActiveWorkbook.FullName
谢谢你的所有评论!
评论