如何解决MS Access VBA导出表到文本文件
我正在使用下面的代码将数据从Access表导出到文本文件,以便可以在MysqL中使用它。
我的导出代码:
Sub ExpTblCity()
On Error GoTo Err_Handler
Dim t,sText,rText,LResult As String
Close #1
t = "INSERT INTO `tblcity` (`city_id`,`city_name`,`city_enabled`) VALUES "
Dim rst As DAO.Recordset
Open Application.CurrentProject.Path & "\2-TblCity.txt" For Output As #1
Print #1,t
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblCity",dbOpenSnapshot)
do while Not rst.EOF
rText = "'NULL'"
sText = "('" & rst!CityID & "','" & rst!City & "','0'),"
LResult = Replace(sText,"NULL")
Print #1,LResult
rst.MoveNext
Loop
rst.Close
Set rst = nothing
t = ""
sText = ""
rText = ""
LResult = ""
Close #1
Exit_This_Sub:
Exit Sub
Err_Handler:
If Err = 0 Then
ElseIf Err = 94 Then
Resume Next
ElseIf Err = 3265 Then
Resume Next
Else
MsgBox "Error #: " & Err.Number & " " & Err.Description
End If
Resume Exit_This_Sub
End Sub
INSERT INTO `tblcity` (`city_id`,`city_enabled`) VALUES
('1','London',('2','Paris',('3','Rome',('4','athens',('5','Madrit',
代码运行良好,但是我试图用; 替换最后的 。
正确的输出:
...
('4','0');
任何想法。
解决方法
使用数组保存它并使用Join函数将很方便。
Sub ExpTblCity()
On Error GoTo Err_Handler
Dim t As String,sText As String,rText As String,LResult As String
Dim vResult() As Variant
Dim n As Long
Close #1
t = "INSERT INTO `tblcity` (`city_id`,`city_name`,`city_enabled`) VALUES "
Dim rst As DAO.Recordset
Open Application.CurrentProject.Path & "\2-TblCity.txt" For Output As #1
Print #1,t
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblCity",dbOpenSnapshot)
Do While Not rst.EOF
n = n + 1
rText = "'NULL'"
sText = "('" & rst!CityID & "','" & rst!City & "','0')"
ReDim Preserve vResult(1 To n)
sText = Replace(sText,rText,"NULL")
vResult(n) = sText
'Print #1,LResult
rst.MoveNext
Loop
sText = Join(vResult,"," & vbCrLf) & ";"
Print #1,sText
rst.Close
Set rst = Nothing
t = ""
sText = ""
rText = ""
LResult = ""
Close #1
Exit_This_Sub:
Exit Sub
Err_Handler:
If Err = 0 Then
ElseIf Err = 94 Then
Resume Next
ElseIf Err = 3265 Then
Resume Next
Else
MsgBox "Error #: " & Err.Number & " " & Err.Description
End If
Resume Exit_This_Sub
End Sub
,
请尝试更改此行:
sText = "('" & rst!CityID & "','0'),"
具有:
If rst.EOF then
sText = "('" & rst!CityID & "','0');"
Else
sText = "('" & rst!CityID & "',"
End If
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。