我有一个旧的数据库表(Name),其字段如下:
ID名称 1a,b,c,d 2 a,b 3 e,f,g 4 5 s,t
只要没有NUlls,就像我在记录4中创建的那样,以下代码
Sub SplitNames()
Dim strNames() As String
Dim ID As Integer
Dim rs As DAO.Recordset
Dim i As Integer
Dim strSql As String
Set rs = CurrentDb.OpenRecordset("Name")
Do While Not rs.EOF
ID = rs!ID
strNames = Split(rs!names, ",")
For i = LBound(strNames) To UBound(strNames)
strSql = "Insert into name2 (ID, Names) values (" & ID & ", '" & strNames(i) & "')"
CurrentDb.Execute strSql
Next i
rs.MoveNext
Loop
End Sub
可以正常解析这些逗号分隔值到第二个表,Name2:
的行ID名称 1 a 1 b 1 c 1 d 2 a 2 b
等
但是当它达到NUll值时,其中有很多,我在这里得到编译错误:
strNames = Split(rs!names, ",")
所以我试着用它来指定一个条件Do,仅用于非空值:
Sub SplitNames()
Dim strNames() As String
Dim ID As Integer
Dim rs As DAO.Recordset
Dim i As Integer
Dim strSql As String
Set rs = CurrentDb.OpenRecordset("Name")
If Not IsNull(rs!names) Then
Do While Not rs.EOF
ID = rs!ID
strNames = Split(rs!names, ",")
For i = LBound(strNames) To UBound(strNames)
strSql = "Insert into Name2 (ID, Names) values (" & ID & ", '" & strNames(i) & "')"
CurrentDb.Execute strSql
Next i
rs.MoveNext
Loop
End If
End Sub
同样,这有效,直到我有一个Null值。相同的代码行。
谢谢你看看。
答案 0 :(得分:0)
这些行的顺序错误:
If Not IsNull(rs!names) Then
Do While Not rs.EOF
这意味着您只在第一条记录中检查Null,并且不检查其他记录。试试这个:
Do While Not rs.EOF
If Not IsNull(rs!names) Then
编辑:宏的结尾也需要像这样改变以避免无限循环:
Next i
End If
rs.MoveNext
Loop
答案 1 :(得分:0)
通过创建选择查询并将其设置为记录集来解决我的问题;不是一个编程解决方案,但它可以工作。