尝试分配邮件合并以打开 excel 文件

问题描述

Sub MyTemplate()

    Dim wordApp As Word.Application
    Dim wordDoc As Word.Document
    Dim wordMailMerge As Word.MailMerge
    Dim wordpath As String
    Dim excelPath As String
       
    CurrentWorksheet = ActiveSheet.Name
    excelPath = ThisWorkbook.Path & "\Sticker Maker.xlsm"

                
                wordpath = ThisWorkbook.Path & "\Inventory Labels.docx"
                Set wordApp = CreateObject("Word.Application")
                Set wordDoc = wordApp.Documents.Open(wordpath)
                Set wordMailMerge = wordDoc.MailMerge
                
                wordMailMerge.OpenDataSource Name:=excelPath,sqlStatement:="SELECT * FROM `'Barcode$'`"
                wordMailMerge.Execute
                'wordDoc.Close
                wordApp.Visible = True

    Set wordMailMerge = nothing
    Set wordDoc = nothing
    Set wordApp = nothing
    Sheets(CurrentWorksheet).Select

End Sub

这段代码中打开excel文件的部分 wordMailMerge.OpenDataSource Name:=excelPath,sqlStatement:="SELECT * FROM 'Barcode$'" 抛出错误,因为文件已经打开。 (该文件代码运行的地方)我只需要它来分配工作簿中的数据而无需打开它。因为它已经打开运行宏。

解决方法

在打开文件时添加只读属性:

wordMailMerge.OpenDataSource Name:=excelPath,ReadOnly:=True,SQLStatement:="SELECT * FROM `'Barcode$'`"