2016-06-10 3 views
-2

이 코드를 온라인으로 검색하여 여러 단어를 강조 표시했습니다. 15 페이지 분량의 문서를 실행하는 데 약 10 분이 걸립니다. 나는 그것이 더 빨리 달릴 수 있는지 궁금해하고 있었다.VBA 단어 코드를 더 빨리 실행하는 방법은 무엇입니까?

Sub HighlightMultipleWords() 
Dim Word As Range 
Dim WordCollection(2) As String 
Dim Words As Variant 
'Define list. 
'If you add or delete, change value above in Dim statement. 
WordCollection(0) = "word1" 
WordCollection(1) = "word2" 
WordCollection(2) = "word3" 
'Set highlight color. 
Options.DefaultHighlightColorIndex = wdYellow 
'Clear existing formatting and settings in Find feature. 
Selection.Find.ClearFormatting 
Selection.Find.Replacement.ClearFormatting 
'Set highlight to replace setting. 
Selection.Find.Replacement.Highlight = True 
'Cycle through document and find words in collection. 
'Highlight words when found. 
For Each Word In ActiveDocument.Words 
For Each Words In WordCollection 
With Selection.Find 
.Text = Words 
.Replacement.Text = "" 
.Forward = True 
.Wrap = wdFindContinue 
.Format = True 
.MatchCase = False 
.MatchWholeWord = False 
.MatchWildcards = False 
.MatchSoundsLike = False 
.MatchAllWordForms = False 
End With 
Selection.Find.Execute Replace:=wdReplaceAll 
Next 
Next 
End Sub 
+0

왜 중첩 루프입니까? 문서의 모든 단일 단어에 대해 컬렉션 (3 개)의 각 단어에 대해 루프 처리를 수행하고 'ReplaceAll'을 실행하는 것처럼 보입니까? 당신은 모든 단어를 검사하고 있으며,이 세 가지를 실행하여 단어를 대치합니다. 바깥 쪽 루프를 잃어 버립니다. – Dave

+0

감사합니다. 나는 그것을 시도 할 것이다. –

+0

[codereview] (http://codereview.stackexchange.com/)에서 게시 할 수 있습니다. 외 루프를 제거하는 것 외에도'Word'와'Words' 변수의 이름을 바꾸어 Word와'.Words'와 혼동하지 않기 바랍니다. – arcadeprecinct

답변

2

주석은 만 찾기를 실행하고 목록에 항목 당 한 번씩 교체해야합니다, 여기에 모든 올바른지, 당신은 문서의 단어의 양에 의해 그것을 여러 번 실행하고 있습니다.

Option Explicit 

Sub HighlightMultipleWords() 
Dim AryWords(2) As String 
Dim VntStore As Variant 

'Define list. 
'If you add or delete, change value above in Dim statement. 
AryWords(0) = "word1" 
AryWords(1) = "word2" 
AryWords(2) = "word3" 

'Set highlight color. 
Options.DefaultHighlightColorIndex = wdYellow 
With Selection.Find 
    'Clear existing formatting and settings in Find feature. 
    .ClearFormatting 
    .Replacement.ClearFormatting 

    'Set highlight to replace setting. 
    Selection.Find.Replacement.Highlight = True 

    'Process the array 
    For Each VntStore In AryWords 
     .Execute FindText:=VntStore, _ 
       MatchCase:=False, _ 
       MatchWholeWord:=False, _ 
       MatchWildcards:=False, _ 
       MatchSoundsLike:=False, _ 
       MatchAllWordForms:=False, _ 
       Forward:=True, _ 
       Wrap:=wdFindContinue, _ 
       Format:=True, _ 
       Replace:=wdReplaceAll 
    Next 
End With 

End Sub 
관련 문제