晚上好!
此时我正在学习在MS Access中工作以实现工作目的。我对该程序的基础知识有了一些了解,比如创建表格或制作简单的表格(虽然还没有理想的工作),到现在为止,我已经陷入了解决以下任务的困境。
我有一个数据库 BooksDatabase ,它由三个表组成: Books , Authors 和 AuthorsInfo 。第一个包含有关书籍的信息(名称,流派,国家,发行年份等),第三个是关于作者(名字,姓氏等),第二个是与作者有关的书籍链接。任务是将数据从文本文件导入到这些表中,这样它几乎是自动的。我理解如何将文件导入MS Access(至少是* .txt扩展名的文件),我在表 BooksToImport 中执行此操作,但是我在插入导入的数据时遇到了一些困难。这是我的函数ImportBooks()的代码,我从同名的宏执行:
' Procedure which imports data about books from the table BooksToImport
Function ImportBooks()
Dim dbBooks As Database
Dim rstImBooks, rstBooks, rstAuthors, rstBALink As DAO.Recordset
Dim codeI, codeB, codeA, codeL As Variant
'initializing database
Set dbBooks = CurrentDb
Set rstImBooks = dbBooks.OpenRecordset("Query_BooksToImport",dbOpenDynaset) 'receiving data from query
'checking if the query has any records
If rstImBooks.RecordCount = 0 Then
MsgBox "There are no records for importing!", vbInformation, "Attention!"
rstImBooks.Close
Set dbBooks = Nothing
Exit Function
End If
'if it's OK, we're making a loop on query's records
rstBooks = dbBooks.OpenRecordset("Books",dbOpenDynaset)
rstAuthors = dbBooks.OpenRecordset("AuthorsInfo",dbOpenDynaset)
rstBALink = dbBoks.OpenRecordset("Authors",dbOpenDynaset)
rstImBooks.MoveLast
rstImBooks.MoveFirst
Do While rstImBooks.EOF = False
'checking if there is a book in out database with the same name as in imported data
codeB = DLookup("[ID]","[Books]","[BookName] = '" & rstImBooks![BookName] & "'")
If IsNull(codeB) Then
'inserting new record
With rstBooks
.AddNew
![BookName] = rstImBooks![BookName]
.Update
.Bookmark = .LastModified
codeB = ![ID]
End With
End If
'in much the same way we're treating the data about authors and making the links
rstImBooks.MoveNext
Loop
rstImBooks.Close
rstBooks.Close
rstAuthors.Close
rstBALink.Close
Set dbBooks = Nothing
End Function
这个功能有两个问题:
所以我的问题是:我应该如何解决这两个问题?我的功能不正常怎么办?
答案 0 :(得分:1)
我看到您的代码存在一些问题。这些可能会或可能不会解决您的问题。
您的声明是隐含的,这意味着您并不特定于您的代码中有关您的记录集对象的内容。而不是使用:
Dim rstImBooks, rstBooks, rstAuthors, rstBALink As DAO.Recordset
尝试:
Dim rstImBooks As DAO.Recordset
Dim rstBooks As DAO.Recordset
Dim rstAuthors As DAO.Recordset
Dim rstBALink As DAO.Recordset
你可以将它们全部放在用逗号分隔的一行上,但你仍然需要为每个都声明类型,否则Access会认为它是一个变体。
其次,记录集对象需要使用Set
关键字创建,而不是仅使用=
。
这在代码的顶部正确完成,但在这里不正确:
rstBooks = dbBooks.OpenRecordset("Books",dbOpenDynaset)
rstAuthors = dbBooks.OpenRecordset("AuthorsInfo",dbOpenDynaset)
rstBALink = dbBoks.OpenRecordset("Authors",dbOpenDynaset)
应该是:
Set rstBooks = dbBooks.OpenRecordset("Books",dbOpenDynaset)
Set rstAuthors = dbBooks.OpenRecordset("AuthorsInfo",dbOpenDynaset)
Set rstBALink = dbBooks.OpenRecordset("Authors",dbOpenDynaset)
我认为这可以解决您的问题,但我没有公正地审核您的代码的每一行。如果您还有问题,请告诉我。
修改强> 发现错字:
rstBALink = dbBoks.OpenRecordset("Authors",dbOpenDynaset)
应该是:
Set rstBALink = dbBooks.OpenRecordset("Authors",dbOpenDynaset)
(错过了dbBooks中的' o'