2009-09-17 2 views
3

개선하기 위해 노력하고있는 Microsoft Word 용 VBA 매크로가 있습니다.검색 할 때 와일드 카드를 가져오고 Microsoft Word 용 VBA 매크로의 함수를 바꿉니다.

매크로의 목적은 문서의 첫 번째 표에있는 검색어와 일치하는 모든 단어를 굵게 표시하고 기울임 꼴로 표시하는 것입니다.

문제는 검색어가 다음되는 와일드 카드를 사용할 수 있습니다 :

하이픈 "-"문자 사이에 공백 또는 기간

별표 (*) "&"중 하나에 대한 와일드 카드 (사이트 이 태그는 이탤릭체 표제어이므로 별표로 표시하지 않으므로 대신 필터를 둘러 보려면 & 심볼을 넣을 것입니다.) 단어의 처음이나 끝에있는 임의의 수의 문자에 대한 와일드 카드. 일반적인 프로그래밍 언어와 달리 단어 중간에 사용되면 하이픈과 결합하여 다양한 문자에 대해 와일드 카드를 사용해야합니다. 예를 들어, "th & -e"는 "th & e"는 표시되지 않지만 "there"는 표시됩니다.

물음표 "?":

내가 지금까지 뭘 하나의 문자에 대한 와일드 카드는 이러한 문자를 테스트하고 그들이 존재하는 경우 나도 별표의 경우에 그들을 베다, 또는 I 사용자에게 단어를 수동으로 검색해야한다고 경고합니다. 이상하지 않습니다 : - P

VBA에서 .MatchWildcard 속성을 시도했지만 아직 작동하지 않았습니다. 검색 텍스트가 아닌 대체 텍스트와 관련이 있다는 느낌이 들었습니다.

모든 번째 열의 테이블이 상상 (:

실제로 동작 매크로 (첫 번째 행 의도적 무시하고, 두 번째 열은 대상 검색어와 하나)의 입력으로서 다음 걸릴 말씀이
두 번째 행 : & earch1
넷째 행 : Search2
세 번째 행 검색 html로는

는 첫 번째 행 TR과 TD 등)을 허용하지 않습니다 여기에 허용되는 03,210
다섯째 행 : S-earch3
여섯 번째 행 : S는
일곱 번째 행 arch4 : S & -ch5

및 그 문서를 검색과 같이 굵은 이탤릭체 콘텐츠로 대체한다 :

검색 Search1 Search2 Search3 Search4 Search5

참고 : Search3도 선택할 수 S.earch 3을 Search3으로 대체하십시오.

일반적으로 검색어가 서로 옆에 있지 않을 수도 있으므로 매크로는 모든 인스턴스를 찾아야합니다.

첫 번째 매크로 작업 후에도 시도했지만 비 기능 코드가 포함됩니다.

작업 매크로의 코드는 오늘부터 9 월 17 일 9 시까 지 (url) 한 달 동안 pastebin에 있습니다.

의견을 보내 주셔서 감사합니다.

사라

작업 VBA 매크로 : 매크로

Sub AllBold() 

Dim tblOne As Table 

Dim celTable As Cell 

Dim rngTable As Range 

Dim intCount As Integer 

Dim celColl As Cells 

Dim i As Integer 

Dim rngLen As Integer 

Dim bolWild As Boolean 

Dim strWild As String 


Set tblOne = ActiveDocument.Tables(1) 

intCount = tblOne.Columns(2).Cells.Count 

Set celColl = tblOne.Columns(2).Cells 

strWild = "" 

For i = 1 To intCount 

    If i = 1 Then 

    i = i + 1 

    End If 

    Set celTable = ActiveDocument.Tables(1).Cell(Row:=i, Column:=2) 

    Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
     End:=celTable.Range.End - 1) 

    rngLen = Len(rngTable.Text) 

    bolWild = False 

    If (Mid(rngTable.Text, rngLen, 1) = "&") Then 'remember to replace & with asterisk!' 

    rngTable.SetRange Start:=rngTable.Start, End:=rngTable.End - 1 

    End If 

    If (Mid(rngTable.Text, 1, 1) = "&") Then 'remember to replace & with asterisk!' 

    rngTable.SetRange Start:=rngTable.Start + 1, End:=rngTable.End 

    End If 

    If InStr(1, rngTable.Text, "-", vbTextCompare) > 0 Then 

    strWild = strWild + rngTable.Text + Chr$(13) 

    bolWild = True 

    End If 

    If InStr(1, rngTable.Text, "?", vbTextCompare) > 0 Then 

    strWild = strWild + rngTable.Text + Chr$(13) 

    bolWild = True 

    End If 

    If (bolWild = False) Then 

     Dim oRng As Word.Range 

      Set oRng = ActiveDocument.Range 

      With oRng.Find 

      .ClearFormatting 

      .Text = rngTable.Text 

      With .Replacement 

      .Text = rngTable.Text 

      .Font.Bold = True 

      .Font.Italic = True 

      End With 

      .Execute Replace:=wdReplaceAll 

    End With 

    End If 

Next 

If bolWild = True Then 

MsgBox ("Please search the following strings with - or ? manually:" + Chr$(13) + strWild) 

End If 

End Sub 

시도 비 기능 VBA :

Sub AllBoldWildcard() 

Dim tblOne As Table 

Dim celTable As Cell 

Dim rngTable As Range 

Dim intCount As Integer 

Dim celColl As Cells 

Dim i As Integer 

Dim rngLen As Integer 

Dim bolWild As Boolean 

Dim strWild As String 

Dim strWildcard As String 


Set tblOne = ActiveDocument.Tables(1) 

intCount = tblOne.Columns(2).Cells.Count 

Set celColl = tblOne.Columns(2).Cells 

strWild = "" 

For i = 1 To intCount 

    If i = 1 Then 

    i = i + 1 

    End If 

    Set celTable = ActiveDocument.Tables(1).Cell(Row:=i, Column:=2) 

    Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
     End:=celTable.Range.End - 1) 

    rngLen = Len(rngTable.Text) 

    bolWild = False 

    If (Mid(rngTable.Text, 1, 1) = "&") Then 'remember to replace & with asterisk!' 

    rngTable.SetRange Start:=rngTable.Start + 1, End:=rngTable.End 

    End If 

    If InStr(1, rngTable.Text, "&", vbTextCompare) > 0 Then 'remember to replace & with asterisk!' 

    strWildcard = rngTable.Text 

    rngTable.Text = Replace(rngTable.Text, "&", "", 1) 'remember to replace & with asterisk!' 

    bolWild = True 

    End If 

    If InStr(1, rngTable.Text, "-", vbTextCompare) > 0 Then 

    strWildcard = Replace(rngTable.Text, "-", "[.-]", 1) 

    bolWild = True 

    End If 

    If InStr(1, rngTable.Text, "?", vbTextCompare) > 0 Then 

    strWild = strWild + rngTable.Text + Chr$(13) 

    strWildcard = Replace(rngTable.Text, "?", "_", 1) 


    bolWild = True 

    End If 

    If (bolWild = False) Then 

     Dim oRng As Word.Range 

      Set oRng = ActiveDocument.Range 

      With oRng.Find 

      .ClearFormatting 

      .Text = strWildcard 

      .MatchAllWordForms = False 

      .MatchSoundsLike = False 

      .MatchFuzzy = False 

      .MatchWildcards = True 


      With .Replacement 

      .Text = rngTable.Text 

      .Font.Bold = True 

      .Font.Italic = True 

      End With 

      .Execute Replace:=wdReplaceAll 

    End With 

    End If 

Next 

' If bolWild = True Then' 

' MsgBox ("Please search the following strings with - or ? manually:" + Chr$(13) + strWild)' 

' End If' 

End Sub 

답변

1
Sub AllBold() 

Dim tblOne As Table 
Dim celTable As Cell 
Dim rngTable As Range 
Dim intCount As Integer 
Dim intMatch As Integer 
Dim celColl As Cells 
Dim i As Integer 
Dim strRegex As String 
Dim Match, Matches 

Set tblOne = ActiveDocument.Tables(1) 
intCount = tblOne.Columns(2).Cells.Count 
Set celColl = tblOne.Columns(2).Cells 
Set objRegEx = CreateObject("vbscript.regexp") 
objRegEx.Global = True 
objRegEx.IgnoreCase = True 
objRegEx.MultiLine = True 

For i = 1 To intCount 
    If i = 1 Then 
     i = i + 1 
    End If 

    Set celTable = ActiveDocument.Tables(1).Cell(Row:=i, Column:=2) 
    Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
             End:=celTable.Range.End - 1) 

    If rngTable.Text <> "" Then 
     strRegex = rngTable.Text 
     strRegex = Replace(strRegex, "*-", "[\w]{0,}[^\w]{0,1}[\w]{0,}", 1) 
     strRegex = Replace(strRegex, "*", "\w+", 1) 
     strRegex = Replace(strRegex, "-", "[^\w]{0,1}", 1) 
     strRegex = Replace(strRegex, "?", ".", 1) 
     objRegEx.Pattern = "\b" + strRegex + "\b" 

     Dim oRng As Word.Range 
     Set oRng = ActiveDocument.Range 
     Set Matches = objRegEx.Execute(ActiveDocument.Range.Text) 

     intMatch = Matches.Count 
     If intMatch >= 1 Then 
      rngTable.Bold = True 
      For Each Match In Matches 
       With oRng.Find 
        .ClearFormatting 
        .Text = Match.Value 
        With .Replacement 
         .Text = Match.Value 
         .Font.Bold = True 
         .Font.Italic = True 
        End With 

        .Execute Replace:=wdReplaceAll 
       End With 
      Next Match 
     End If 
    End If 
Next i 

End Sub 
+0

그래서 결국 Match.FirstIndex를 사용할 수 없다는 것이 드러났습니다. 문서가 설정된 방식으로 테이블이 떨어져 버렸기 때문입니다. 나는 Range for를 사용하기보다는 Match.Value를 찾기 위해 Match For Each에서 Word Find를 사용했다. 이것은 제가 찾고 있던 정확한 해결책입니다. 당신이 없이는 할 수 없었습니다. 우리 둘 사이에이 솔루션이 완벽하게 작동했습니다. – saranicole

+0

내가 당신을 도울 수 있다는 말을 듣고 반갑습니다. – jantimon

1

은 아마 LIKE 문을 사용하면 도움이 될 수 :

if "My House" like "* House" then 

end if 

정기 EXPRES을 sions : Search4을 검색하고 SEARCH4로 교체하고 그것을 달성하기 위해 와일드 카드를 사용하여 :

Set objRegEx = CreateObject("vbscript.regexp") 
objRegEx.Global = True 
objRegEx.IgnoreCase = True 
objRegEx.MultiLine = True 

'here you can enter your search with wild cards 
'mine says "S" followed by any character followed by "arch" followed by 1-n numbers. 
objRegEx.Pattern = "S.arch([0-9]+)" 


newText = objRegEx.Replace("Test Search4", "SEARCH$1") 
MsgBox (newText) 
'gives you: Test SEARCH4 
사용하는 와일드 카드는 here 그것은 처음에는 어려울 수 있지만 나는 당신을 사랑합니다 약속 발견 할 수있는 방법을

상세 정보 그것은)

당신은 너무 문자열을 검색하기 위해 사용을 대체 할 수

희미한 텍스트 문자열 텍스트 = "안녕하세요 Search4 search3 sAarch2의 search0 검색"으로

Set objRegEx = CreateObject("vbscript.regexp") 
objRegEx.Global = True 
objRegEx.IgnoreCase = True 
objRegEx.MultiLine = True 

'here you can enter your search with wild cards 
'mine says "S" followed by any character followed by "arch" followed by 1-n numbers. 
objRegEx.Pattern = "S.arch[0-9]+" 


If (objRegEx.test(text) = True) Then 
    Dim objMatch As Variant 
    Set objMatch = objRegEx.Execute(text) ' Execute search. 

    Dim wordStart As Long 
    Dim wordEnd As Long 
    Dim intIndex As Integer 
    For intIndex = 0 To objMatch.Count - 1 
     wordStart = objMatch(intIndex).FirstIndex 
     wordEnd = wordStart + Len(objMatch(intIndex)) 

     MsgBox ("found " & objMatch(intIndex) & " position: " & wordStart & " - " & wordEnd) 
    Next 
End If 

변수 텍스트에 대한 결과는 다음과 같습니다

Search4 position: 6 - 13 
Search3 position: 14- 21 
... 

그래서 코드에서 원하는 범위를 것

rngTable.Text as text 

rngTable.SetRange Start:=rngTable.Start + wordStart, End:=rngTable.Start + wordEnd 

을 사용 굵게 설정하십시오.

+1

게시 해 주셔서 감사합니다. 이 말이 맞지만, 검색과 대체에서 "like"가 사용되는 방법을 보여주는 코드 예제를 찾으려고합니다. 운이 좋으면 "좋아요"라는 단어가 영어 이외의 다른 의미로 코드에서 자주 사용되므로 너무나 까다로운 검색 엔진에 문제가 있습니다! ;-) VBA 찾기를 사용하여 코드 예제를 게시하거나 설명하는 자습서로 연결되는 링크를 게시 할 수 있습니까? 많은 의무가 있습니다! – saranicole

+0

얼마나 달콤한 당신입니까 ?? 코드 주셔서 감사합니다 - 나는 이것이 vbscript에 있음을 알았습니다 - 그것이 VBA와 호환 될 것입니까? 나는 VBA가 정규 표현식을 지원한다고 생각하지 않았고, 와일드 카드만을 사용했다. (다른 것들은 내가 먼저 가지고 있었던 것이다. MS 오피스 개발을 좋아한다 .-P) – saranicole

+0

당신을 환영한다. MS Word 2008을 사용하여 샘플 코드를 사용해 보았습니다. VBA는 afaik VBScript와 MS Office Api입니다. – jantimon

관련 문제