2017-05-18 49 views
0

我正在构建一个数据库来存放Word文档和数据。在这张表格中附有一份文件的副本。如何从Access表中打开附件

如何使用VBA从Field1(默认名称)引用并打开附加文件(word文档)的副本?

我试过使用DAO Recordset,但仍然遇到bug。 Attachment上的对象引用文件几乎没有任何帮助。

如果需要其他信息,请让我知道。谢谢!

Private Sub Field1_AfterUpdate() 
'Outline: 
'Macro is on Form_Entry. After user uploads an attachment into the DB via form, 
'I would like to open a copy of the attachment 
'and perform additional actions on the document 

'Declarations 
    Dim Active_DB As DAO.Database 
    Dim Active_Q As DAO.QueryDef 
    Dim Active_RS, iRS As DAO.Recordset 
    Dim Active_Field As DAO.Field 

'Refresh form such new entry is created 
    Forms!Entry.Refresh 

'Connect DB 
    Set Active_DB = CurrentDb 
    Set Active_RS = Forms!Entry.Recordset 

'Retrieve recordset of the current record entry. 
    Active_RS.FindFirst "ID =" & Forms!Entry.ID.Value 

'This is where I run into problems. I am not sure what the command is to open a document. 
    Set Active_Field = Active_RS!Field1.Open 

    Debug.Print Active_Field.FileName 

End Sub 
+2

没有代码的问题往往会被关闭 - 即使您的代码有错误,最好包含它。 –

+0

@TimWilliams。谢谢你的提示。我编辑了我的帖子:)! – DVCode

+1

无法直接从记录集打开文档:将其保存到文件并从那里打开 –

回答

1

谢谢大家的帮助。

基于评论,我能够通过保存和打开临时文件进行处理来绕过这个问题。

Private Sub Field1_AfterUpdate() 
'Declarations 
    'Access-Related 
    Dim Active_DB As DAO.Database 
    Dim Active_Q As DAO.QueryDef 
    Dim Active_RST, parent_RST, child_RST As DAO.Recordset 
    Dim Active_Field As DAO.Field 

    'Word-Related 
    Dim app_Word As Word.Application 
    Dim Active_DOC As Word.Document 

    'Varible Declaration 
    Dim str_Dir, str_FName As String 


    'Refresh to create record 
    Forms!entry.Refresh 


    'Initial Assignments 
    str_Dir = Environ("Temp") & "\" 

    Set Active_DB = CurrentDb 
    Set Active_RST = Forms!entry.Recordset 


    'Assign Record Set to Current Record 
    Active_RST.FindFirst "ID =" & Forms!entry.ID.Value 

    'Assign Field value 
    Set parent_RST = Active_RST.Fields("Field1").Value 
    Set Active_Field = parent_RST.FileData 

    'Create Word Application & document Objects 
    Set app_Word = CreateObject("Word.application") 

    If Dir(str_Dir & parent_RST.FileName) = "" Then 
     'If directory does not exist, create SaveToFiles 
     'Else open Document 
     Active_Field.SaveToFile str_Dir & parent_RST.FileName 
    End If 
    Set Active_DOC = Documents.Open(str_Dir & parent_RST.FileName) 


    Contract_Text.Value = str_Dir & parent_RST.FileName 

End Sub