我正在使用手动创建的表Products的空副本,我将其命名为Products_Backup。我想要做的是将“Spices”类别的产品中的每隔一行插入到这个空的Products_Backup表中,因为总共12行中只有6行,这些行位于“Spices”类别下的Products表中。问题是我不知道该怎么做。我尝试将MOD运算符用于新创建的ProductID,但我的导师告诉我这不是一个合适的解决方案,因为他可以轻松更改此ProductID的值,我会得到奇数行而不是偶数。
Private Sub CommandButton0_Click()
Dim db As Database, rst As Recordset
Dim I As Integer, s, s1 As String
Set db = CurrentDb
s = "SELECT Products.* FROM Products WHERE (((Products.CategoryNumber)=2));" ' This value is for Spices
Set rst = db.OpenRecordset(s)
I = 1
While Not rst.EOF
s1 = "INSERT INTO Products_Backup (ProductName, ProductID, CategoryNumber, OrderedUnits) VALUES ('" & rst!ProductName & "', " & I & " , '" & rst!CategoryNumber & "', '" & rst!OrderedUnits & "');"
MsgBox ("Record inserted")
db.Execute s1
I = I + 1
rst.MoveNext
If I Mod 10 = 0 Then
MsgBox ("Inserted " & I & ".record")
End If
Wend
rst.Close
db.Close
End Sub
因此,我可以将所有12条记录插入Products_Backup,MsgBox告诉我何时插入了第10条记录。 但我仍然不知道如何将每隔一行插入Products_Backup以获得6条记录。
答案 0 :(得分:2)
Dim booEveryOther as Boolean
booEveryOther = False
While Not rst.EOF
If booEveryOther Then
s1 = "INSERT INTO ...
End If
booEveryOther = Not booEveryOther
只需使用每个新记录设置为Not
的布尔值。
答案 1 :(得分:0)
我认为这应该做得更好
While Not rst.EOF
s1 = " INSERT INTO Products_Backup (ProductName, ProductID, CategoryNumber, OrderedUnits) " & _
" VALUES ('" & rst!ProductName & "', " & I & " , '" & rst!CategoryNumber & "', '" & rst!OrderedUnits & "');"
db.Execute s1
If I Mod 10 = 0 Then
MsgBox ("Inserted " & I & ".record")
Else
MsgBox ("Record inserted")
End If
I = I + 1
rst.MoveNext
Wend