sql - VBA/Access INSERT into 将数字字符串作为数字传递的语句
问题描述
我正在将工作簿中的数据读入访问表中。我遇到的麻烦是我在文本格式的单元格中有数字数据,这些数据有一个前导零,当 INSERT into 语句读取它时,它会切断前导零。传递给它的数据具有前导零,并且它进入的表列是文本格式。
是否有解决方法让 SQL 将数字字符串作为字符串传递?
您看到的各种 msgbox 用于调试目的。
Dim StringVar As Variant
Dim strLn As String
'Asks user for Filepath
StringVar = InputBox("Please enter file path", "Import", "")
'Ends Function if no input or cancel is detected
MsgBox (StringVar)
If StringVar = "" Or StringVar = False Then
MsgBox ("No input, Please try again")
Exit Sub
End If
'Scrubs outer quotes if present
StringVar = Replace(StringVar, Chr(34), "", 1, 2)
MsgBox ("File Path Checked")
Dim FSO As Object
Set FSO = CreateObject("Scripting.Filesystemobject")
'Checks that our file exists, exits if not
If (Not FSO.FileExists(StringVar)) Then
MsgBox ("File does not exist, try again")
Exit Sub
End If
Dim xlApp As Object 'Excel.Application
Dim xlWrk As Object 'Excel.Workbook
Dim xlSheet As Object 'Excel.Worksheet
Dim i As Long
MsgBox ("working on an excel sheet")
Set xlApp = VBA.CreateObject("Excel.Application")
'toggle visibility for debugging
xlApp.Visible = False
Set xlWrk = xlApp.Workbooks.Open(StringVar) 'opens the excel file for processing
Set xlSheet = xlWrk.Sheets("Sheet1") 'modify to your perticular sheet
MsgBox ("About to change the format")
xlSheet.Columns("A").NumberFormat = "@"
MsgBox ("Format changed")
'walks through the excel sheet to the end and inserts the lines below the headerline into the database
For i = 2 To xlSheet.UsedRange.Rows.Count
DoCmd.RunSQL "Insert Into Split_List(Criteria) values(" & xlSheet.Cells(i, 1).Value & ")"
If (MsgBox(i, vbOKCancel) = vbCancel) Then Exit Sub
Next i
MsgBox ("Brought in " & i & " lines")
'Quits the file and closes the object
xlWrk.Save
xlWrk.Close
xlApp.Quit
Set xlSheet = Nothing
Set xlWrk = Nothing
Set xlApp = Nothing
解决方案
我在这个问题中找到了我的问题的答案,我 应该在 SQL 中引用数字吗?
我没有将作为代码的 ID 作为字符串传递,而是将它们作为数字传递,因此在 Insert Into 语句中我将“xlSheet.Cells(i, 1).Value”放入 SQL 语句中围绕该值,因此它作为字符串传递
声明应如下所示
DoCmd.RunSQL "Insert Into Split_List(Criteria) values('" & xlSheet.Cells(i, 1).Value & "')"
^ ^
推荐阅读
- angular - 如何从组件添加状态属性
- android - 如果没有连接,调用请求的最佳做法是每 4-5 秒重复一次调用,直到我们得到响应,使用 Rx
- dart - 如何将资产图像转换为文件?
- sql - Microsoft SQL Server 接受变量名称中的空白 - 为什么?
- node.js - 将 MongoDB 中的 JSON 文件导入 Nodejs 应用程序的最佳实践
- android - WebView 在显示来自 Google Docs 的 PDF 时随机打开白屏
- c# - 使用应用程序连接到 Service Fabric
- angular - Angular 语言服务在 VSCode 中不起作用
- c++ - 如何使用 ffmpeg 实现类似 get_next_frame 的功能?
- html - 如何使按钮与搜索栏内联?