[求助]我是个把数据库数据写到文本文件里面,为什么运行的时候说对象变量或with块变量未定义

lzx14125 2006-04-21 08:38:33
Option Explicit
Dim db As Database '定义一个DAO数据库对象
Dim strtable As String '指定Access数据库中的表名

' Export the file.
Private Sub cmdExport_Click()
Dim fnum As Integer
Dim file_name As String
Dim database_name As String

Dim rs As Recordset
Dim num_fields As Integer
Dim field_width() As Integer
Dim field_value As String
Dim i As Integer
Dim num_processed As Integer

On Error GoTo MiscError
' Open the output file.
fnum = FreeFile
file_name = txtFileName.Text
Open file_name For Append As fnum

strtable = List1.Text


Set rs = db.OpenRecordset("SELECT * FROM " & strtable)

'把数据库中表的字段名称导出到文本文件中
num_fields = rs.Fields.Count
ReDim field_width(0 To num_fields - 1)
For i = 0 To num_fields - 1

field_width(i) = rs.Fields(i).Size
If field_width(i) < Len(rs.Fields(i).Name) Then
field_width(i) = Len(rs.Fields(i).Name)
End If
field_width(i) = field_width(i) + 1
Print #fnum, rs.Fields(i).Name;
Print #fnum, Space$(field_width(i) - _
Len(rs.Fields(i).Name));
Next i
Print #fnum, ""

' 把数据库表中数据按记录导出到文本文件中
Do While Not rs.EOF
num_processed = num_processed + 1
For i = 0 To num_fields - 1
field_value = rs.Fields(i).Value
Print #fnum, field_value & _
Space$(Abs(field_width(i) - _
Len(field_value)));
Next i
Print #fnum, ""
rs.MoveNext
Loop

' Close the file and database.
rs.Close
db.Close
Close fnum
MsgBox "Processed " & _
Format$(num_processed) & " records."

Exit Sub

MiscError:
MsgBox "Error " & Err.Number & _
vbCrLf & Err.Description
End Sub

Private Sub Command1_Click()
CommonDialog1.Filter = "数据库文件(*.mdb)|*.mdb"
CommonDialog1.ShowOpen
txtDatabaseName.Text = CommonDialog1.FileName
End Sub

Private Sub Command2_Click()
CommonDialog1.Filter = "文本文件(*.txt)|*.txt"
CommonDialog1.ShowOpen
txtFileName.Text = CommonDialog1.FileName
End Sub

Private Sub Command3_Click()
' 打开数据库并且把数据库中的表名显示在列表框中
Set db = OpenDatabase(txtDatabaseName.Text)

RefreshList

End Sub

Private Sub Form_Load()
txtDatabaseName.Text = App.Path & "\15.mdb"
txtFileName.Text = App.Path & "\15.txt"
End Sub
Private Sub RefreshList() '刷新List1的内容
Dim i As Integer
List1.Clear
For i = db.TableDefs.Count - 1 To 0 Step -1
If db.TableDefs(i).Attributes = 0 Then
List1.AddItem (db.TableDefs(i).Name)
End If
Next
End Sub
...全文
94 1 点赞 打赏 收藏 举报
写回复
1 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
province_ 2006-04-21
Dim db As Database 改为 Dim db As New Database
  • 打赏
  • 举报
回复
相关推荐
发帖
VB基础类
加入

7543

社区成员

VB 基础类
申请成为版主
帖子事件
创建了帖子
2006-04-21 08:38
社区公告
暂无公告