当我尝试执行命令将新行插入数据库时,抛出错误。我相信Null值会引发错误。虽然我不能确定。
这是我的代码:
Sub AddRows()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim comm As ADODB.Command
Set comm = New ADODB.Command
Dim param As ADODB.Parameter
Dim getType As MultipleValues
Dim nullCheck As String
SQLStr = "Insert Into [Steve_Dev_Matrix] Values("
For i = 1 To 121
'Get type
SQLStr = SQLStr & "?,"
Set param = New ADODB.Parameter
param.Name = "Param" & i
Set param = comm.CreateParameter("param" & i, CLng(CellType(i, Cells(2, i).Value).CellType), adParamInput, CellType(i, Cells(2, i).Value).CellNum)
param.Attributes = adParamNullable
'Debug.Print (param.Type)
comm.Parameters.Append param
Next i
SQLStr = Left(SQLStr, Len(SQLStr) - 1) & ");"
Set Cn = New ADODB.Connection
Cn.CommandTimeout = 0
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
comm.ActiveConnection = Cn
comm.CommandText = SQLStr
comm.CommandType = adCmdText
Dim test As String
lastrow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
'For x = 2 To lastrow
For i = 1 To 121
Debug.Print (comm.Parameters.Item("Param" & i).Type)
comm.Parameters.Item("Param" & i).Value = Cells(2, i).Value
Next
comm.Execute
' Tidy up
Cn.Close
Set Cn = Nothing
End Sub
此处还有CellType方法的示例:
Private Function CellType(Num, Rng) As MultipleValues
Application.Volatile
Select Case True
Case Num = 1
CellType.CellType = adInteger
Case Num = 2
CellType.CellType = adInteger
Case Num = 3
CellType.CellType = adVarWChar
CellType.CellNum = 255
Case Num = 4
CellType.CellType = adCurrency
Case Num = 5
CellType.CellType = adVarWChar
CellType.CellNum = 255
错误说明:使用默认参数
无效