Помогите изменить MS Word Macro для использования строки вместо замены диалогового окна - PullRequest
1 голос
/ 21 мая 2011

Я нашел этот макрос для Word, который заменяет текст где угодно (верхние колонтитулы, нижние колонтитулы, текстовые поля), и это то, что мне нужно, но единственная проблема заключается в том, что он использует диалоговое окно замены. Что мне нужно, это использовать строку в макросе для замены. Но как бы я ни старался, я не могу заставить его работать.

Кто-нибудь захочет помочь? Вот оригинальный макрос ( из MVP ), который мне нужно изменить, чтобы использовать строку, а не диалоговое окно замены (поле ввода):

Public Sub FindReplaceAnywhere()
  Dim rngStory As Word.Range
  Dim pFindTxt As String
  Dim pReplaceTxt As String
  Dim lngJunk As Long
  Dim oShp As Shape
  pFindTxt = InputBox("Enter the text that you want to find." _
    , "FIND" )
  If pFindTxt = "" Then
    MsgBox "Cancelled by User"
    Exit Sub
  End If
  TryAgain:
  pReplaceTxt = InputBox( "Enter the replacement." , "REPLACE" )
  If pReplaceTxt = "" Then
    If MsgBox( "Do you just want to delete the found text?", _
     vbYesNoCancel) = vbNo Then
      GoTo TryAgain
    ElseIf vbCancel Then
      MsgBox "Cancelled by User."
      Exit Sub
    End If
  End If
  'Fix the skipped blank Header/Footer problem
  lngJunk = ActiveDocument.Sections( 1 ).Headers( 1 ).Range.StoryType
  'Iterate through all story types in the current document
  For Each rngStory In ActiveDocument.StoryRanges
    'Iterate through all linked stories
    Do
      SearchAndReplaceInStory rngStory, pFindTxt, pReplaceTxt
      On Error Resume Next
      Select Case rngStory.StoryType
      Case 6 , 7 , 8 , 9 , 10 , 11
        If rngStory.ShapeRange.Count > 0 Then
          For Each oShp In rngStory.ShapeRange
            If oShp.TextFrame.HasText Then
              SearchAndReplaceInStory oShp.TextFrame.TextRange, _
                  pFindTxt, pReplaceTxt
            End If
          Next
        End If
      Case Else
        'Do Nothing
      End Select
      On Error GoTo 0
      'Get next linked story (if any)
      Set rngStory = rngStory.NextStoryRange
    Loop Until rngStory Is Nothing
  Next
End Sub
Public Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, _
    ByVal strSearch As String , ByVal strReplace As String )
  With rngStory.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = strSearch
    .Replacement.Text = strReplace
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
  End With
End Sub

А вот пример того, что я имею в виду, используя строку вместо текста вместо диалогового окна (я хочу заменить несколько вещей одновременно - StrOld заменяется StrNew):

Sub MultiReplaceAtCursor()
Dim StrOld As String, StrNew As String
Dim RngFind As Range, RngTxt As Range, i As Long
StrOld = "°|©|H"
StrNew = "¾|¶|e"
Set RngTxt = Selection.Range
For i = 0 To UBound(Split(StrOld, "|"))
  Set RngFind = RngTxt.Duplicate
  With RngFind.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = Split(StrOld, "|")(i)
    .Replacement.Text = Split(StrNew, "|")(i)
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
  End With
Next
End Sub

Спасибо за вашу помощь! * 1011 Натан *

Ответы [ 2 ]

1 голос
/ 22 мая 2011
Public Sub FindReplaceAnywhere()
Dim oldString, newString As String ' The two strings you want
Dim rngStory As Word.Range
Dim pFindTxt As String
Dim pReplaceTxt As String
Dim lngJunk As Long
Dim oShp As Shape
oldString = "Your string to find" ' Replace this value by the string to find
newString = "Your replacement" ' Replace this value string by the replacement you want
'Fix the skipped blank Header/Footer problem
lngJunk = ActiveDocument.Sections( 1 ).Headers( 1 ).Range.StoryType
'Iterate through all story types in the current document
For Each rngStory In ActiveDocument.StoryRanges
     'Iterate through all linked stories
     Do
       SearchAndReplaceInStory rngStory, oldString, newString
       On Error Resume Next
       Select Case rngStory.StoryType
       Case 6 , 7 , 8 , 9 , 10 , 11
           If rngStory.ShapeRange.Count > 0 Then
               For Each oShp In rngStory.ShapeRange
                   If oShp.TextFrame.HasText Then   
                       SearchAndReplaceInStory oShp.TextFrame.TextRange, _ oldString, newString
                   End If
               Next       
           End If       
       Case Else         'Do Nothing 
       End Select      
       On Error GoTo 0       'Get next linked story (if any)   
       Set rngStory = rngStory.NextStoryRange    
   Loop Until rngStory Is Nothing  
Next
End Sub

Public Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, _ ByVal strSearch As String , ByVal strReplace As String )  
With rngStory.Find
     .ClearFormatting
     .Replacement.ClearFormatting
     .Text = strSearch
     .Replacement.Text = strReplace
     .Wrap = wdFindContinue
     .Execute Replace:=wdReplaceAll
   End With
End Sub 
1 голос
/ 22 мая 2011

если я вас правильно понимаю, минимум, что вы можете сделать, это заменить

pFindTxt = InputBox("Enter the text that you want to find.", "FIND" )

на

pFindTxt = "string to find"

и

pReplaceTxt = InputBox( "Enter the replacement." , "REPLACE" )

на

pReplaceTxt = "replacement"

в вашем первом примере, где "string to find" - это то, что вы заменяете, а "replacement" - это текст, которым вы хотите заменить его.Это удалит диалоговые окна и явно установит, что вы хотите найти / заменить.Это так просто?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...