我有一個excel工作簿,它是一個項目計劃模板,PM填充信息並將其加載到sql數據庫中。目前該過程是否通過裝載兩個表的批處理過程(1個具有1行數據,另一個具有多個記錄)。我正在改變它是一個直接從excel插入到SQL Server通過vba插入。我有插入工作,但每個表都有一個項目ID列,這是PK。下午可能更新並保存該文件多次。表格會根據最新的保存信息進行更新。我已經通過在代碼中添加刪除語句並插入更新的記錄來解決此問題。這對於有1條記錄的表格非常有用,但是我無法獲得帶有多條記錄的表格。它會刪除記錄,並通過插入的第一個循環,然後返回到刪除並刪除記錄。在插入之前刪除SQL服務器表中的記錄
我附加了多表刪除和插入的代碼。有人能告訴我我做錯了什麼嗎?
Public Sub exportprojdetaildata()
Dim stSQL As String
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim iRowNo As Integer
Dim targetedFieldNames As Variant
Dim rowData As Variant
Dim lastrow As Long
Dim sql As String
Dim i As Integer
Dim cvt As Double
Dim aField As String
Dim compare As Variant
Dim value As Variant
Dim dvalue As Long
With Sheets("Data")
lastrow = .Range("A:A").Find(what:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
'Open a connection to SQL Server
conn.Open _
"Provider=SQLOLEDB;Data Source=PWIRTPAUDD1HV8;Initial Catalog=STAR;User Id=STAR_USER;Password=dcistarrtp"
'Skip the header row
iRowNo = 2
targetedFieldNames = Join(WorksheetFunction.Transpose(wks_TargetFieldNames.Range("targetedFieldNames").value), "," & vbNewLine)
Do While iRowNo <= lastrow
rowData = wks_BackgroundData.Range("A" & iRowNo & ":AV" & iRowNo).value
compare = wks_BackgroundData.Range("AV2").value
'Generate and execute sql statement to import the excel rows to SQL Server table
With rs
.ActiveConnection = conn
.Open "Select proj_id from dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy where proj_id = " & compare
wks_BackgroundData.Range("BA2").CopyFromRecordset rs
.Close
End With
value = wks_BackgroundData.Range("BA2").value
If compare = value Then
sql = "delete from dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy where proj_id = " & value
conn.Execute sql
Else
sql = "insert into dbo.STAR_DC_INITIAL_ProjectDetails_ExcelDevCopy ("
sql = sql & targetedFieldNames
' Debug.Print sql
sql = sql & ") values (" & vbNewLine
' Debug.Print sql
'couldn't do transpose since rowData represents a row, not a column
For i = 1 To UBound(rowData, 2)
aField = Replace(rowData(1, i), "'", "''")
'escape single quotes
Select Case i
Case 1, 6, 16, 17, 23 To 47
' cvt = CDbl(aField)
If aField = vbNullString Then
sql = sql & "Null," & vbNewLine
Else
sql = sql & aField & "," & vbNewLine
End If
Case 2 To 5, 7 To 15, 18 To 22
sql = sql & "'" & aField & "', " & vbNewLine
Case 48
If aField = vbNullString Then
sql = sql & "Null"
Else
sql = sql & aField
End If
End Select
Next i
sql = sql & ");"
'sql = sql & "');"
' End If
conn.Execute sql
iRowNo = iRowNo + 1
Loop
End If
conn.Close
Set conn = Nothing
End With
末次
你不應該使用VBA來做到這一點。 –
然後我應該使用什麼? – ncwright
如果您希望PM通過Excel進行更新,那麼我明白您爲什麼要使用vba進行更新並與您達成一致。您可以在1行(標題)表上添加刪除觸發器,當記錄從那裏刪除時,它會刪除多行(詳細)表。或者添加一個外鍵並在刪除時啓用級聯刪除。 – Dbloch