这似乎是一个常见的问题,但我似乎无法得到答案。
我从excel文件中使用VBA读出的表包含一个字段,该字段具有由逗号分隔符分隔的多个值。我知道这样做的正确方法是规范化这个领域。我似乎无法让我的解决方案工作。
我的表看起来像这样:
ProdID | Color | Value
1 | Blue, Green | 30
2 | White, Blue, Red | 50
3 etc.
我试图通过首先将它们放在临时表中然后更新主要表来分割值,但这看起来很麻烦,我怀疑必须有一个更智能的解决方案......
'check that data is available and copy data to new temporary sheet
rowCount = wks.UsedRange.Rows.count
If rowCount < 2 Then
MsgBox ("The Workbook " & wkb & " contains no Data. The Process will not continue to execute!")
GoTo EndCleanUp
Else
'delete old data in DB table
With tblMorningstarFS
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM " & .Name
DoCmd.SetWarnings True
End With
'create array with prod color id set
Dim tempArray()
ReDim tempArray(rowCount, 1)
With wks
For i = 0 To rowCount
tempArray(i, 0) = .Cells(i + 1, 1) ' prodID
tempArray(i, 1) = .Cells(i + 1, 2) ' colorID
Next i
End With
'create temporary table
curDatabase.Execute "CREATE TABLE tempColorTable " _
& "(ProdID CHAR, ColorID CHAR);"
'fill prodID/colorID table with array info
With curDatabase.OpenRecordset("tempColorTable", dbOpenTable)
For i = 1 To UBound(tempArray, 1) + 1
.AddNew
rs.Fields("ProdID") = wks.Range("A" & i + 1).Value
rs.Fields("ColorID") = wks.Range("C" & i + 1).Value
rs.Update
Next i
End With
'update the exisiting table with information
Dim SQL As String
SQL = "INSERT INTO tblProd_Color ( ProdID, ColorID ) " & _
"SELECT tempColorTable.ProdID, tempColorTable.ColorID " & _
"FROM tempColorTable"
DoCmd.RunSQL SQL
'fill prod table with value information
With wks
For i = 1 To rowCount
rs.AddNew
rs.Fields("PRODUCT") = .Range("A" & i + 1).Value
rs.Fields("VALUE") = .Range("C" & i + 1).Value
rs.Update
Next i
End With
With wks
For i = 1 To rowCount
rs.AddNew
rs.Fields("PRODUCT") = .Range("A" & i + 1).Value
rs.Fields("VALUE") = .Range("C" & i + 1).Value
rs.Update
Next i
End With
End If
此代码还没有完全发挥作用,但在我投入时间使其工作之前,我想知道我是否至少在正确的轨道上。
感谢您的任何意见!
答案 0 :(得分:0)
我有同样的情况。 我使用[HeaderTable&lt; --- DetailTable]结构通过执行以下步骤来解决问题。
1. Created a Header table that stores all the "Header Data", in your case ProdID,Value
2. Created a table containing "Detail Data" in your case ProdID,RowNo,Color
3. Insert all Row's ProdID into Header Table
4. Split the values in the field Color based on index of (,)Comma. For each Substring insert a row into Detail table with ProdID,RowNo,Substring as color.