【问题标题】:HOW To manipulate an ALREADY open word document from excel vba如何从 excel vba 操作已经打开的 word 文档
【发布时间】:2021-03-26 21:32:04
【问题描述】:

我是 VBA 新手,显然我遗漏了一些东西。我的代码适用于打开 word doc 并向其发送数据但不适用于 ALREADY OPEN word doc。我一直在寻找有关如何将信息从 Excel 发送到 OPEN Word 文档/书签的答案,但没有任何效果。

我希望我添加了所有代码和调用的函数是可以的。非常感谢您的帮助!

我目前拥有的东西

Sub ExcelNamesToWordBookmarks()
On Error GoTo ErrorHandler

Dim wrdApp As Object 'Word.Application
Dim wrdDoc As Object 'Word.Document
Dim xlName As Excel.Name
Dim ws As Worksheet
Dim str As String 'cell/name value
Dim cell As Range
Dim celldata As Variant 'added to use in the test
Dim theformat As Variant 'added
Dim BMRange As Object
Dim strPath As String
Dim strFile As String
Dim strPathFile As String

Set wb = ActiveWorkbook
strPath = wb.Path
If strPath = "" Then
  MsgBox "Please save your Excel Spreadsheet & try again."
  GoTo ErrorExit
End If

'GET FILE & path of Word Doc/Dot
strPathFile = strOpenFilePath 'call a function in MOD1

If strPathFile = "" Then
  MsgBox "Please choose a Word Document (DOC*) or Template (DOT*) & try again." 'strPath = Application.TemplatesPath
  GoTo ErrorExit
End If

    If FileLocked(strPathFile) Then 'Err.Number = 70 if open
    'read / write file in use 'do something
    'NONE OF THESE WORK
        Set wrdApp = GetObject(strPathFile, "Word.Application")
        'Set wrdApp = Word.Documents("This is a test doc 2.docx")
    'Set wrdApp = GetObject(strPathFile).Application
    Else
    'all ok 'Create a new Word Session
            Set wrdApp = CreateObject("Word.Application")
            wrdApp.Visible = True
            wrdApp.Activate 'bring word visiable so erros do not get hidden.
    'Open document in word
            Set wrdDoc = wrdApp.Documents.Open(Filename:=strPathFile) 'Open vs wrdApp.Documents.Add(strPathFile)<=>create new Document1 doc
    End If

'Loop through names in the activeworkbook
    For Each xlName In wb.Names

            If Range(xlName).Cells.Count = 1 Then
                  celldata = Range(xlName.Value)
                  'do nothing
               Else
                  For Each cell In Range(xlName)
                     If str = "" Then
                        str = cell.Value
                     Else
                        str = str & vbCrLf & cell.Value
                     End If
                  Next cell
                  'MsgBox str
                  celldata = str
               End If

'Get format and strip away the spacing, negative color etc etc
'I know this is not right... it works but not best
            theformat = Application.Range(xlName).DisplayFormat.NumberFormat
            If Len(theformat) > 8 Then
                theformat = Left(theformat, 5) 'was 8 but dont need cents
            Else
                'do nothing for now
            End If

        If wrdDoc.Bookmarks.Exists(xlName.Name) Then
            'Copy the Bookmark's Range.
            Set BMRange = wrdDoc.Bookmarks(xlName.Name).Range.Duplicate
            BMRange.Text = Format(celldata, theformat)
            'Re-insert the bookmark
            wrdDoc.Bookmarks.Add xlName.Name, BMRange
        End If

    Next xlName


'Activate word and display document
  With wrdApp
      .Selection.Goto What:=1, Which:=2, Name:=1  'PageNumber
      .Visible = True
      .ActiveWindow.WindowState = wdWindowStateMaximize 'WAS 0 is this needed???
      .Activate
  End With
  GoTo WeAreDone

'Release the Word object to save memory and exit macro
ErrorExit:
    MsgBox "Thank you! Bye."
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
   Exit Sub

'Error Handling routine
ErrorHandler:
   If Err Then
      MsgBox "Error No: " & Err.Number & "; There is a problem"
      If Not wrdApp Is Nothing Then
        wrdApp.Quit False
      End If
      Resume ErrorExit
   End If

WeAreDone:
Set wrdDoc = Nothing
Set wrdApp = Nothing

End Sub

文件挑选:

Function strOpenFilePath() As String
Dim intChoice As Integer
Dim iFileSelect As FileDialog 'B

Set iFileSelect = Application.FileDialog(msoFileDialogOpen)

With iFileSelect
    .AllowMultiSelect = False 'only allow the user to select one file
    .Title = "Please... Select MS-WORD Doc*/Dot* Files"
    .Filters.Clear
    .Filters.Add "MS-WORD Doc*/Dot*  Files", "*.do*"
    .InitialView = msoFileDialogViewDetails
End With

'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strOpenFilePath = Application.FileDialog( _
    msoFileDialogOpen).SelectedItems(1)
Else
    'nothing yet
End If

End Function

检查文件是否打开...

Function FileLocked(strFileName As String) As Boolean
   On Error Resume Next
   ' If the file is already opened by another process,
   ' and the specified type of access is not allowed,
   ' the Open operation fails and an error occurs.
   Open strFileName For Binary Access Read Write Lock Read Write As #1
   Close #1
   ' If an error occurs, the document is currently open.
   If Err.Number <> 0 Then
      ' Display the error number and description.
      MsgBox "Function FileLocked Error #" & str(Err.Number) & " - " & Err.Description
      FileLocked = True
      Err.Clear
   End If
End Function

【问题讨论】:

  • 你试过了吗:Set wrdApp = GetObject(, "Word.Application")
  • 我做到了...在第一次运行后,所有良好的数据和数据都从 excel 传输到 word。然后在 2nd run 更新 OPEN 字文档,代码返回错误 91(未设置对象变量)并且错误处理程序终止字。 (不再记忆中)

标签: vba excel ms-word


【解决方案1】:

答案如下。 背景故事...所以,在你们的输入和更多研究之后,我发现我需要通过使用文件选择来设置活动的 Word 文档用户选择,然后通过后期绑定传递给子作为要处理的对象。现在,如果 word 文件不在 word 中,或者如果它当前加载到 word 中,甚至不是活动文档,它就可以工作。下面的代码替换了我原来问题中的代码。

  1. 将对象应用设置为单词。
  2. 获取文件名。
  3. 激活选中的单词 doc 以进行操作。
  4. 将单词对象设置为活动文档。

谢谢大家!

If FileLocked(strPathFile) Then 'Err.Number = 70 if open
'read / write file in use 'do something
    Set wrdApp = GetObject(, "Word.Application")
    strPathFile = Right(strPathFile, Len(strPathFile) - InStrRev(strPathFile, "\"))
    wrdApp.Documents(strPathFile).Activate ' need to set picked doc as active
    Set wrdDoc = wrdApp.ActiveDocument ' works!

【讨论】:

  • 我的荣幸!我希望这对其他人有帮助:-)
【解决方案2】:

这应该可以得到你需要的对象。

Dim WRDFile As Word.Application
Set WRDFile = GetObject(strPathFile)

【讨论】:

  • 谢谢,但它说“未定义用户定义类型”
  • 你需要添加对 Ms-Word 的引用,因为 mooseman 的代码正在使用早期绑定。
  • (快速搜索后是“包含对 Microsoft Word 对象模型的引用。从工具 | 参考中执行此操作,然后添加对 MS Word 的引用。”)但我不能这样做代码将发给一群不会打开此功能的人等等。
  • 好的...我已经将 wrdApp 作为对象,所以我在 If 文件锁定中添加了 Set wrdApp = GetObject(strPathFile),我收到错误 91 和 438。
  • 非常感谢您的回复!但我完全被困住了......我的代码内部有解决方案吗?想知道如何将 excel 数据添加到 已经打开 word 文件中的 word 书签,这让我发疯了?
【解决方案3】:

'在您的参考文献中选择了 Microsoft Word 16.0 对象库

Dim wordapp As Object
Set wordapp = GetObject(, "Word.Application")

wordapp.Documents("documentname").Select

' 如果您只有一个打开的 Word 文档,则可以使用。就我而言,我正在尝试将更新从 excel 推送到单词链接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多