簡體   English   中英

VBA for Word中的查找/替換字符限制解決方法

[英]Find/Replace character limit workaround in VBA for Word

我有一個基本的vbscript,可以在Microsoft Word中查找和替換,但是我無法遍歷一定數量的字符(我認為是256)。 我想知道是否有人對這個問題有解決辦法。 以下是我正在使用的腳本示例:

Sub FixedReplacements()
Dim Rng As Range
Dim SearchString As String
Dim EndString As String
Dim Id As String
Dim Link As String

Rng.Find.ClearFormatting
Rng.Find.Replacement.ClearFormatting
With Rng.Find
    .Text = "" 'find text won't exceed character limitation'
    .Replacement.Text = "" 'replace text won't exceed character limitation'
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Rng.Find.Execute Replace:=wdReplaceAll   

Find().Text沒有限制。 檢查一下:

Option Explicit

Sub TestMe()

    Dim myRange As Range
    Set myRange = ActiveDocument.Content

    Dim lookFor As String
    lookFor = "The text to be searched for. Use an empty string () to search for formatting only. You can search for special characters by specifying appropriate character codes. For example, corresponds to a paragraph mark and corresponds to a tab character."
    myRange.Find.Execute FindText:=lookFor, ReplaceWith:="hello", Replace:=wdReplaceAll

End Sub

限制部分可能是一條線,該線未在要查找的字符串中正確解析,因此找不到該線。

要查找太長的文本,請搜索字符串的前255個字符,然后將找到的范圍擴展到其他字符。 或將字符串分解為255個字符的“位”,然后連續搜索(始終將第一個找到的范圍擴展到每個后續找到的范圍的終點)。

可以使用太長的文本進行替換,但不能使用Replace 而是循環將字符串值分配給找到的范圍。 (請注意,需要將Wrap設置為wdFindStop 。)

Dim bFound As Boolean
Dim replacementText as String
Dim findText as String, excessText as String
Dim excessChars as Long, bTooLong as Boolean

findText = "Text to be found..."
If Len(findText) > 255 Then
   bToolLong = True
   excessText = Mid(findText, 256)
   excessChars = Len(excessText)
   findText = Left(findText, 255)
End If
replacementText = "some long string greater than 256 characters"
With Rng.Find
    .Text = findText
    '.Replacement.Text = "" 'replace text won't exceed character limitation'
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
bFound = Rng.Find.Execute
Do While bFound
    If bTooLong Then
      Rng.End = Rng.End + excessChars
      'Possible to check findText against the range
      'If Rng.Text <> findText Then 'do something
    End If
    Rng.Text = replacementText
    Rng.Collapse wdCollapseEnd
    bFound = Rng.Find.Execute
Loop

我花了很長時間尋找一種簡單的解決方案。 為了那些也拖網漁船的利益,請考慮我的解決方案。

我的假設是有一次要替換的文本。

  1. 查找您要替換的文本
  2. 在之后插入newtext
  3. 使用查找和替換,刪除找到的文本

     With WordDoc.Content .Find.Execute findText:="text", Forward:=True, Wrap:=wdFindStop .InsertAfter Text:="newtext" .Find.Execute findText:="text", ReplaceWith:="" End With 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM