【发布时间】:2017-12-07 00:08:20
【问题描述】:
我有一个每天生成的特定工作文档,其中包括一段文本,然后是一个包含一堆客户数据的表格。我需要将该数据导入 Access 表中。
我找到了代码,我将在下面包含它,它就是这样做的。但是它没有按预期工作。相反,它根本不起作用。我预计这是因为 doc 这个词不是以表格开头,而是以文本开头。
所以我有两个选择。 1) 找到一种方法来格式化每个文档,使其仅包含表格(我必须自动执行此操作,因为我们每天都会收到几十个这样的文件)或 2) 调整代码以便它检测 only 文档中的表格。
有没有做这些事情的好方法?
Option Compare Database
Private Sub cmdImport_Click()
Dim appWord As Word.Application, doc As Word.Document
Dim dbs As DAO.Database, rst As DAO.Recordset, strDoc As String
Set appWord = CreateObject("Word.Application") 'establish an instance of word
strDoc = CurrentProject.Path & "\cmoSheet.docx" 'set string to document path and file
Set doc = appWord.Documents.Open(strDoc) 'establish the document
Set dbs = CurrentDb 'establish the database to use (this is our current Database)
Set rst = dbs.OpenRecordset("cmoSheetTbl") 'establish the recordset
With doc.Tables(1) 'target table 1 in cmoSheet.docx
For i = 2 To .Rows.Count 'cycle through rows in Tables(1) [we skip the first row because the table has headers]
With rst
.AddNew 'creating a new record
![ReviewerName] = doc.Tables(1).Cell(i, 1).Range.Text
![ProductDesc] = doc.Tables(1).Cell(i, 2).Range.Text
![NPI] = doc.Tables(1).Cell(i, 3).Range.Text
![LastName] = doc.Tables(1).Cell(i, 5).Range.Text
![FirstName] = doc.Tables(1).Cell(i, 6).Range.Text
![ProviderType] = doc.Tables(1).Cell(i, 7).Range.Text
![Specialty] = doc.Tables(1).Cell(i, 8).Range.Text
![BatchID] = doc.Tables(1).Cell(i, 9).Range.Text
![AdditionalDocs?] = doc.Tables(1).Cell(i, 10).Range.Text
.Update 'update the whole record
End With
Next 'go to next row in Tables(1)
End With
rst.Close: Set rst = Nothing 'close and clear recordset
db.Close: Set rst = Nothing 'close and clear database
doc.Close: Set doc = Nothing 'close and clear document
appWord.Quit: Set appWord = Nothing 'close and clear MS Word
End Sub
【问题讨论】:
标签: ms-access import ms-word vba