简体   繁体   English

VBA 从 Excel 更新 Word 中的书签 - 仅运行一次?

[英]VBA updating bookmarks in Word from Excel - Only Runs Once?

I have the code below in Excel which is designed to use information entered into the spreadsheet to populate bookmarks in various Word documents.我在 Excel 中有以下代码,该代码旨在使用输入到电子表格中的信息来填充各种 Word 文档中的书签。 For context, I need to produce multiple documents using 90% of the same information and holding all relevant info in an Excel sheet makes this easier.就上下文而言,我需要使用 90% 的相同信息生成多个文档,并将所有相关信息保存在 Excel 工作表中使这更容易。

My spreadsheet allows me to produce up to five documents using the information entered into the worksheet.我的电子表格允许我使用输入到工作表中的信息生成最多五个文档。 I set how many documents need to be produced when filling out the form.我在填写表格时设置了需要生成多少文件。 There are 5 variations of the document that can be produced and the code is designed to check what type is needed, open that file that is designed for that type and populate with the data.可以生成文档的 5 种变体,代码旨在检查需要什么类型,打开为该类型设计的文件并填充数据。

The issue I'm having is that when I open Excel and run the macro the first time it works fine - it opens the relevant Word doc(s), populates them with the data, updates the fields and saves the updated document.我遇到的问题是,当我第一次打开 Excel 并运行宏时,它可以正常工作 - 它会打开相关的 Word 文档,用数据填充它们,更新字段并保存更新的文档。

If I try and run the macro again however, it does not populate the bookmarks in the document(s).但是,如果我再次尝试运行宏,它不会填充文档中的书签。 The document still gets saved but it is no different than the base template.文档仍然会被保存,但它与基本模板没有什么不同。

If I close Excel, reopen it and run the macro, it works fine for one run.如果我关闭 Excel,重新打开它并运行宏,它可以正常运行一次。

I have tried some of the debugging and the issue appears to be with this part of the code:我已经尝试了一些调试,问题似乎出在这部分代码上:

On Error Resume Next
   Set wd = GetObject(, "Word.Application")
   If Err <> 0 Then
       Set wd = CreateObject("Word.Application")
   End If

In my debugging I added a message box to see if the if Err <> 0 is correct.在我的调试中,我添加了一个消息框来查看 if Err <> 0 是否正确。 The first time the macro runs on opening word it reaches the line:宏第一次在打开单词时运行,它到达以下行:

Set wd = CreateObject("Word.Application")

On subsequent runs though is only returns:在随后的运行中,只返回:

Set wd = GetObject(, "Word.Application")

I have tried setting both to Set wd = CreateObject("Word.Application") but that does not work.我尝试将两者都设置为 Set wd = CreateObject("Word.Application") 但这不起作用。

Thoughts?想法? my code is below.我的代码如下。

Thanks in advance for your help.在此先感谢您的帮助。

Sub GteeDisc()
 'Dim OutApp As Outlook.Application
 'Dim OutMail As Outlook.MailItem
 Dim wb As Workbook
 Dim wt As Worksheet
 Dim wd As New Word.Application
 Dim mail_doc As Word.Document
 'Dim email_text As Word.Document
 Dim objInspector As Object
 Dim objDoc As Object
 
 Dim Borrower_Name As String
 Dim Bank_Name As String
 
 Dim Gtor_Name As String
 Dim Gtee_Limit As String
 Dim Max_term As String
 Dim max_term_unit As String
 Dim GteeLimit As String
 Dim Total_borrowing As String
 Dim Loan_type As String
 Dim total_loans As String
 Dim Gtor_entity As String
 Dim Total_Guarantees As Integer
 
 
 
 
 
 
    'Set wb = ActiveWorkbook
    'Worksheets("Lending Details").Activate
    'Set wt = ActiveSheet
    
    Set wt = ThisWorkbook.Worksheets("Lending Details")
    
    Borrower_Name = wt.Range("B2").Text
    Bank_Name = wt.Range("E3").Text
    
    
    Max_term = wt.Range("L7").Value
    max_term_unit = wt.Range("L8").Value
    'Total_borrowing = wt.Range("L6").Value
    
   
    
    If wt.Range("L9").Value = "Revolving Credit Facility" Then
    Loan_type = "RCF"
    Else
    Loan_type = "Non-RCF"
    End If
   
  Total_Guarantees = wt.Range("B121").Value
  If Total_Guarantees > 0 Then
   For i = 1 To Total_Guarantees
   
   If i = 1 Then
    Gtor_entity = wt.Range("B123").Value
    Gtor_Name = wt.Range("B124").Value
    Gtee_Type = wt.Range("B125").Value
    Gtee_Limit = wt.Range("B126").Value
   ElseIf i = 2 Then
    Gtor_entity = wt.Range("B129").Value
    Gtor_Name = wt.Range("B130").Value
    Gtee_Type = wt.Range("B131").Value
    Gtee_Limit = wt.Range("B132").Value
   ElseIf i = 3 Then
    Gtor_entity = wt.Range("B135").Value
    Gtor_Name = wt.Range("B136").Value
    Gtee_Type = wt.Range("B137").Value
    Gtee_Limit = wt.Range("B138").Value
   ElseIf i = 4 Then
    Gtor_entity = wt.Range("B141").Value
    Gtor_Name = wt.Range("B142").Value
    Gtee_Type = wt.Range("B143").Value
    Gtee_Limit = wt.Range("B144").Value
   ElseIf i = 5 Then
    Gtor_entity = wt.Range("B147").Value
    Gtor_Name = wt.Range("B149").Value
    Gtee_Type = wt.Range("B150").Value
    Gtee_Limit = wt.Range("B151").Value
   End If
    'is Gtee Limited or unlimited
    If Gtee_Type = "Limited" Then
    Gtee_Type = "Limited"
    Else
    Gtee_Type = "Unlimited"
    End If
    
     
    
    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If Err <> 0 Then
       Set wd = CreateObject("Word.Application")
    End If
    
    
    
    If Gtor_entity = "Individual" Then
    Set mail_doc = wd.Documents.Open("C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\04 - Gurantees\GDL & Waiver - Individual.docx")
    
    ElseIf Gtor_entity = "Couple" Then
    Set mail_doc = wd.Documents.Open("C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\04 - Gurantees\GDL & Waiver - Couple.docx")
    
    ElseIf Gtor_entity = "Company" Then
    Set mail_doc = wd.Documents.Open("C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\04 - Gurantees\GDL & Waiver - Company.docx")
    
    ElseIf Gtor_entity = "Partnership" Then
    Set mail_doc = wd.Documents.Open("C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\04 - Gurantees\GDL & Waiver - Company.docx")
    
    ElseIf Gtor_entity = "Trust" Then
    Set mail_doc = wd.Documents.Open("C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\04 - Gurantees\GDL & Waiver - Trust.docx")
    
    End If
    Application.Wait (Now + TimeValue("0:00:02"))
    
    
    
    With mail_doc
    
    UpdateBookmarkContent "bmBankName", Bank_Name
    UpdateBookmarkContent "bmBorrowerName", Borrower_Name
    UpdateBookmarkContent "bmGtorName", Gtor_Name
    UpdateBookmarkContent "bmGtorName1", Gtor_Name
    
    UpdateBookmarkContent "bmtotalBorrowing", Format(CDbl(wt.Range("L6").Value), "#,##0.00")
        
    UpdateBookmarkContent "bmMaxTerm", Max_term
    UpdateBookmarkContent "bmMaxTermunit", max_term_unit
    
    If Gtee_Type = "Limited" Then
    'UpdateBookmarkContent "bmGteeLimit", Gtee_Limit
    UpdateBookmarkContent "bmGteeLimit", Format(CDbl(Gtee_Limit), "#,##0.00")
    UpdateBookmarkContent "bmGuaranteeLimit", "Limited Guarantee"
    UpdateBookmarkContent "bmGuaranteeLimit2", "Guarantee Limited to $" & Format(CDbl(Gtee_Limit), "#,##0.00")
    UpdateBookmarkContent "bmGuaranteeLimit3", "a guarantee limited to $" & Format(CDbl(Gtee_Limit), "#,##0.00")
    
    mail_doc.Bookmarks("bmUnlimitedGtee").Range.Font.Hidden = True
    
    Else
    UpdateBookmarkContent "bmGuaranteeLimit", "Unlimited Guarantee"
    UpdateBookmarkContent "bmGuaranteeLimit3", "an unlimited guarantee"
    End If
    
    
   
    
           
    mail_doc.Fields.Update
    
    
    
    mail_doc.SaveAs Filename:="C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\07 - Generated Docs\GDL & Waiver - " & Gtor_Name & ".docx"
    'mail_doc.ExportAsFixedFormat OutputFileName:="C:\Users\tsiso\Dropbox\HLS Convey\Documents\01 - Refinance\07 - Generated Docs\DM Request Letter - " & Bank_Name & " (" & Client_Name & ").pdf", ExportFormat:=wdExportFormatPDF
    End With
    
    mail_doc.Close
    
  Next i
End If
Application.ScreenUpdating = True
'mail_doc.Close
'wd.Quit
Set mail_doc = Nothing
Set wd = Nothing
'MsgBox "Done!"
End Sub

[Update] [更新]

So I have done some more testing on this and still cannot get it to work.因此,我对此进行了更多测试,但仍然无法使其正常工作。 The main issue appears to be with this part of the code:主要问题似乎与这部分代码有关:

On Error Resume Next
Set wd = GetObject(, "Word.Application")
If Err <> 0 Then
   Set wd = CreateObject("Word.Application")
End If

From what I can tell from testing, when the code runs the line从我从测试中可以看出,当代码运行该行时

set wd = GetObject(, "Word.Application")

the macro works and updates the word doc.宏工作并更新word doc。 When the macro runs the lines当宏运行这些行时

If Err <> 0 Then
           Set wd = CreateObject("Word.Application")

The macro does not work宏不起作用

In terms of the function that is used within this code, it is as follows:就这段代码中使用的函数而言,如下所示:

Function UpdateBookmarkContent(strBookMarkName As String, strNewText As String) As String
    Dim oRangeBKM As Word.Range
    If ActiveDocument.Bookmarks.Exists(strBookMarkName) Then
        Set oRangeBKM = ActiveDocument.Bookmarks(strBookMarkName).Range
        oRangeBKM.Text = strNewText
        ActiveDocument.Bookmarks.Add strBookMarkName, oRangeBKM
    End If
End Function

Summary What I am trying to achieve is a word doc is opened, bookmarks within that word doc are updated with data from the Excel sheet.总结 我想要实现的是打开一个 word 文档,用 Excel 工作表中的数据更新该 word 文档中的书签。 Several of these bookmarks are updated and the bookmark retained so that fields in Word doc that refer to them can be updated.更新了其中几个书签并保留了书签,以便可以更新 Word 文档中引用它们的字段。

Any assistance with where I am going wrong in my code would be appreciated.任何有关我的代码出错的地方的帮助将不胜感激。 Thanks谢谢

I can't see that you need any of the GetObject or CreateObject code.我看不出您需要任何 GetObject 或 CreateObject 代码。 You already create a new Word application object with Dim wd As New Word.Application ... and the New instantiates the object.您已经使用Dim wd As New Word.Application ... 创建了一个新的 Word 应用程序对象,并且New实例化了该对象。 All you then need to do is open the document .. work on it ... and close it again.然后您需要做的就是打开文档……处理它……然后再次关闭它。 Eg a simple example ...例如一个简单的例子......

Option Explicit

Sub Example()
    
    Dim wd As New Word.Application
    Dim mail_doc As Word.Document
    
    Set mail_doc = wd.Documents.Open("C:\test1.docx")
    mail_doc.SaveAs Filename:="C:\test2.docx"
    mail_doc.Close
    wd.Quit
    
End Sub

(Also, given the for loop, I assume that Gtor_Name remains unique between iterations ... so that the .SaveAs doesn't overwrite the same document). (另外,考虑到 for 循环,我假设Gtor_Name在迭代之间保持唯一......以便.SaveAs不会覆盖同一个文档)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM