【发布时间】:2022-12-26 01:12:17
【问题描述】:
如何使用 VBA 将 Excel 中的空值或空白值传递给 SQL Server?
当我的代码读取一个空白单元格时,即使它有数据,下一个后续单元格也将是空白的。
我试图在单元格为空时输入 null,但我在处理日期时遇到了问题,因为我在 SQL Server 中日期列的数据类型是日期,因此它无法将“null”读取为日期。
此外,我的 SQL 查询中出现运行时错误(“',' 附近的语法不正确”)。
Public Sub UploadData()
Dim count As Long
Dim start As Integer
Dim i As Long
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.Open "Provider=SQLOLEDB;Data Source=10.206.88.119\BIWFO;" & _
"Initial Catalog=TESTDB;" & _
"Uid=user; Pwd=pass;"
Dim cmd As ADODB.Command
Dim pm As ADODB.Parameter
If MsgBox("This will IMPORT everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
Dim rng As Range: Set rng = Range("A2", Range("A2").End(xlToRight).End(xlDown))
Dim row As Range
count = ActiveSheet.Cells(Rows.count, "A").End(xlUp).row
i = 2
OpenStatusBar
Do While i <= count
For Each row In rng.Rows
RequestID = row.Cells(1).Value
IssuingCountryName = row.Cells(2).Value
ProgramStructure = row.Cells(3).Value
LineOfBusinessName = row.Cells(4).Value
RequestGrossPremiumAmount = row.Cells(5).Value
RequestCollectionCurrencyName = row.Cells(6).Value
Clientname = row.Cells(7).Value
ROServiceContact = row.Cells(8).Value
RequestEffectiveDate = row.Cells(9).Value
RequestReleaseDate = row.Cells(10).Value
OriginalRequestReleaseDate = row.Cells(11).Value
RequestType = row.Cells(12).Value
RequestStatus = row.Cells(13).Value
RequestRejectDate = row.Cells(14).Value
RequestRejectReason = row.Cells(15).Value
RequestCorrectionDate = row.Cells(16).Value
RequestAcceptedDate = row.Cells(17).Value
RequestLocalBookDate = row.Cells(18).Value
PolicyIssuedDate = row.Cells(19).Value
IOAccountHandlerContact = row.Cells(20).Value
SQL = " INSERT INTO [TESTDB].[dbo].[tbl_MN_Daily_SLA] " _
& " Values('" & RequestID & "' , '" & IssuingCountryName & "' , '" & ProgramStructure & "' , '" & LineOfBusinessName & "' , " _
& " " & RequestGrossPremiumAmount & " ,'" & RequestCollectionCurrencyName & "' , '" & Clientname & "' , '" & ROServiceContact & "' , " _
& " '" & RequestEffectiveDate & "' , '" & RequestReleaseDate & "' , '" & OriginalRequestReleaseDate & "' , '" & RequestType & "' , '" & RequestStatus & "' ," _
& " '" & RequestRejectDate & "' , '" & RequestRejectReason & "' , '" & RequestCorrectionDate & "' , '" & RequestAcceptedDate & "' , '" & RequestLocalBookDate & "' , " _
& " '" & PolicyIssuedDate & "' , '" & IOAccountHandlerContact & "')"
con.Execute SQL
DoEvents
Call RunStatusBar(i, count)
i = i + 1
count = Range("A2", Range("A2").End(xlDown)).count
Next row
Loop
Unload StatusBar
con.Close
MsgBox "Done Importing"
End Sub
【问题讨论】:
标签: sql-server excel vba