创建一个循环以将 Excel 上传到 SQL 数据酶



所以我下面有一些代码,应该循环访问行和列并将条目上传到SQL DB(使用Ado)。连接和一切正常,我只是在努力理解为什么字符串没有正确构造。我在打开局部变量的情况下观看了它,似乎每次迭代都会重置 strValues,这使得它毫无用处。

Sub generic_lookup()
Dim lngRow As Long, lngCol As Long, strSQL As String, strValues As String
lngRow = Sheets("Upload").Cells(Rows.Count, 1).End(xlUp).Row + 1
lngCol = Sheets("Upload").Cells(6, Columns.Count).End(xlToLeft).Column + 1
strSQL = "INSERT INTO mytable (value1, value2, value3)" & vbNewLine
For i = 6 To lngRow
strValues = strValues & "select " & ""
For X = 1 To lngCol
strValues = Sheets("Upload").Cells(lngRow, lngCol)
Next X
strValues = Left(strValues, Len(strValues)) & vbNewLine
strValues = strValues & " from dual union all" & vbNewLine
Next i
If strValues <> "" Then
strValues = Left(strValues, Len(strValues) - 11)
strSQL = strSQL & strValues
conn.Execute (strSQL)
strValues = ""
strSQL = ""
End If
conn.Close
Set conn = Nothing
End Sub

我不太确定如何解决此问题并将值保持在 strValues 中。任何帮助都非常感谢!

我认为问题是您实际上并没有在循环中选择值。

您需要添加.Value.以下是调整后的代码:

Sub generic_lookup()
Dim lngRow As Long, lngCol As Long, strSQL As String, strValues As String
lngRow = Sheets("Upload").Cells(Rows.Count, 1).End(xlUp).Row + 1
lngCol = Sheets("Upload").Cells(6, Columns.Count).End(xlToLeft).Column + 1
strSQL = "INSERT INTO mytable (value1, value2, value3)" & vbNewLine
For i = 6 To lngRow
strValues = strValues & "select " & ""
Dim addedAValue As Boolean
blnAddedAValue = False
For x = 1 To lngCol
Dim strCellValue As String
strCellValue = Sheets("Upload").Cells(lngRow, lngCol).Value
If Not StrComp(strCellValue, "") Then
If Not blnAddedAValue Then
strValues = strValues & strCellValue
blnAddedAValue = True
Else:
strValues = strValues & strCellValue & ", "
End If
End If
Next x
strValues = Left(strValues, Len(strValues)) & vbNewLine
strValues = strValues & " from dual union all" & vbNewLine
Next i
If strValues <> "" Then
strValues = Left(strValues, Len(strValues) - 11)
strSQL = strSQL & strValues
conn.Execute (strSQL)
strValues = ""
strSQL = ""
End If
conn.Close
Set conn = Nothing
End Sub

值得注意的是,您仍然在X循环中多次覆盖strValues- 您确定您是故意这样做的吗?

编辑:上面的代码更新为仅添加到现有的strValues字符串中。布尔值检查是否需要用逗号添加下一个值。根据需要进行调整。

最新更新