简体   繁体   English

需要从 MS Excel 中的列表中扩展 MS Word 中的多重查找和替换,以替换带有超链接的文本并修复错误

[英]Need to expand Multiple find and replace in MS Word from a list in MS Excel to replace text w hyperlink and fix error

I have a large Word file that refers to multiple Question #s throughout.我有一个很大的 Word 文件,它在整个过程中都引用了多个问题 #。 I also have an Excel file that lists all the Question #s in Column A and in Column B there is a list of actual questions that are also hyperlinks.我还有一个 Excel 文件,其中列出了 A 列中的所有问题 #,而 B 列中有一个实际问题列表,这些问题也是超链接。 I would like to replace every question # in the Word document with the corresponding hyperlinked question in Column B of the spreadsheet.我想将 Word 文档中的每个问题 # 替换为电子表格 B 列中相应的超链接问题。

I tried to use the macro in the StackOverflow question Multiple find and replace in MS Word from a list in MS Excel , but I get the我尝试使用 StackOverflow 问题中的宏在MS Word 中从 MS Excel 的列表中多次查找和替换,但我得到了

Run-time error '1004': Unable to get the Special Cells property of the Range class.运行时错误“1004”:无法获取 Range 类的特殊单元格属性。

I am not sure what this means or how to fix it.我不确定这意味着什么或如何解决它。 Also I am guessing this macro needs adjusting to be able to insert the hyperlinked text that is in Column B.另外我猜这个宏需要调整才能插入 B 列中的超链接文本。

Thanks for any help!谢谢你的帮助! PS We have been doing this manually and annually for 4 guides with over 100 questions in each guide for the past 15 years. PS 在过去的 15 年中,我们一直在手动和每年为 4 个指南执行此操作,每个指南中有 100 多个问题。 I so want to figure out a way to automate!!我很想找到一种自动化的方法!!

The problem with the code in the link is that it's written for late binding but nevertheless uses a named Excel constant.链接中代码的问题在于它是为后期绑定而编写的,但仍然使用了一个命名的 Excel 常量。 Change 'xlCellTypeLastCell' to '11'.将“xlCellTypeLastCell”更改为“11”。

Since you're wanting to hyperlink the questions, try something along the lines of:由于您想要超链接问题,请尝试以下方法:

Sub HyperlinkQuestions()
Application.ScreenUpdating = False
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String, r As Long
Dim StrFnd As String, StrHLnk As String, StrHTxt As String
StrWkBkNm = "C:\Users\" & Environ("Username") & "\Documents\QuestionLinks.xlsx"
If Dir(StrWkBkNm) = "" Then
  MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
  Exit Sub
End If
On Error Resume Next
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
  MsgBox "Can't start Excel", vbExclamation
  Exit Sub
End If
On Error GoTo 0
With xlApp
  'Hide our Excel session
  .Visible = False
  ' The file is available, so open it.
  Set xlWkBk = .Workbooks.Open(StrWkBkNm, False, True)
  If xlWkBk Is Nothing Then
    MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
    .Quit: Set xlApp = Nothing: Exit Sub
  End If
  ' Process the workbook.
  With xlWkBk
    With .Worksheets("Sheet1")
      'Process the F/R data
      For r = 2 To .Cells(.Rows.Count, 1).End(-4162).Row ' -4162 = xlUp
        If Trim(.Range("A" & r)) <> vbNullString Then
          StrFnd = .Range("A" & r).Text
          With .Range("B" & r)
            If .Hyperlinks.Count = 1 Then
              StrHLnk = .Hyperlinks(1).Address
              StrHTxt = .Hyperlinks(1).TextToDisplay
            Else
              StrHLnk = .Text
              StrHTxt = .Text
            End If
          End With
          Call LinkQuestion(StrFnd, StrHLnk, StrHTxt)
        End If
      Next
    End With
  .Close False
  End With
  .Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
Application.ScreenUpdating = True
End Sub

Sub LinkQuestion(StrFnd As String, StrHLnk As String, StrHTxt As String)
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = StrFnd
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = True
    .MatchWholeWord = True
    .Execute
  End With
  Do While .Find.Found
    .Hyperlinks.Add .Duplicate, StrHLnk, , , StrHTxt
    .Start = .Hyperlinks(1).Range.End
    .Find.Execute
  Loop
End With
End Sub

Running the 'HyperlinkQuestions' macro will turn your questions into hyperlinks.运行“HyperlinkQuestions”宏会将您的问题变成超链接。

The macro assumes you're using an Excel workbook named 'QuestionLinks.xlsx' stored in your 'Documents' folder and the Question & Hyperlink list are in Columns A & B, respectively, of 'Sheet1'.该宏假定您使用的是名为“QuestionLinks.xlsx”的 Excel 工作簿,该工作簿存储在“文档”文件夹中,问题和超链接列表分别位于“Sheet1”的 A 列和 B 列中。

Based on your sample files:根据您的示例文件:

Sub ReplaceInWordWithLinks()

    Dim wsName As String, ws As Worksheet, oWord As Object, oDoc As Object
    Dim cQNum As Range, qText As String, qContent As String, qLink As String
    Dim lnk As Hyperlink

    wsName = "TestLinkswLinks"

    Set ws = ThisWorkbook.Worksheets(wsName)

    Set oWord = GetObject(, "Word.application") 'get the open Word application
    Set oDoc = oWord.activedocument

    Set cQNum = ws.Range("A1") 'first question

    'do while cell is not blank
    Do While Len(cQNum.Value) > 0

        qText = Trim(cQNum.Value)
        'add trailing period if missing
        If Right(qText, 1) <> "." Then qText = qText & "."
        qContent = cQNum.Offset(0, 1).Value
        'is there an associated link?
        Set lnk = Nothing
        qLink = ""
        On Error Resume Next
        Set lnk = cQNum.Offset(0, 1).Hyperlinks(1)
        On Error GoTo 0
        If Not lnk Is Nothing Then qLink = lnk.Address

        Debug.Print qText, qContent, qLink

        ReplaceQuestionWithLink oDoc, qText, qContent, qLink

        Set cQNum = cQNum.Offset(1, 0) 'next question
    Loop

End Sub

'Replace all occurences of question with content and a link
'  qText = 'Question 3.' (eg)
Function ReplaceQuestionWithLink(doc As Object, qText As String, _
                                 qContent As String, qLink As String)
    Dim rng As Object

    Set rng = doc.Range

    ResetFindParameters rng 'reset Find to defaults

    With rng.Find
        .Text = qText
        Do While .Execute
            rng.Select
            doc.Parent.ActiveWindow.ScrollIntoView rng, True
            rng.Text = qContent             'replace text
            If Len(qLink) > 0 Then
                doc.Hyperlinks.Add rng, qLink   'add link if present
            End If
        Loop
    End With

End Function


Sub ResetFindParameters(oRng As Object)
  With oRng.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = 1 'wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = True '<<
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
  End With
End Sub

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

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