Macro de VBA de Word en parentheticals

0

Pregunta

He estado usando la siguiente macro para sacar los elementos entre paréntesis a los comentarios en la palabra:

'
' CommentBubble Macro
'
'
Dim myRange As Range
Set myRange = ActiveDocument.Content
searchtext = "\(*\)"

With myRange.Find
    .MatchWildcards = True
    Do While .Execute(findText:=searchtext, Forward:=True) = True
      If Len(myRange.Text) > 4 Then
        ActiveDocument.Comments.Add myRange, myRange.Text
        myRange.Text = ""
      End If
    Loop
 End With
End Sub

La razón por la que tengo la longitud del texto > 4 es debido a que estos son documentos legales y no quiero aislar las cadenas que tienen cosas como "en las siguientes condiciones: (i) la condición 1, (ii) la condición 2, etc".

Sin embargo, aquí es un fragmento de texto para que el código anterior se rompe:

This is sample text (with some additional text) that does stuff (with more stuff) and represents 39.4% of shares on the effective date (before giving effect, with some conditions such as ( some stuff (i) and some stuff (ii) with final stuff) and more final stuff) which is subject to  (some conditions here) and conclude here. 

Si ejecuta este obtendrá el siguiente resultado:

This is sample text  that does stuff  and represents 39.4% of shares on the effective date  and some stuff (ii) with final stuff) and more final stuff) which is subject to   and conclude here. 

Como se puede ver el paréntesis anidados causar algunos problemas. Algún consejo?

Gracias!

ms-word vba
2021-11-20 22:17:27
1

Mejor respuesta

2

Usted está tratando de coincidir con los paréntesis que en palabra es una Palabra de difícil e ingrata tarea como Palabra sólo se ve la apertura y el cierre de paréntesis como personajes individuales y no coinciden automáticamente con la palabra. El código de abajo en busca de coincidencias entre paréntesis, elimina los espacios en blanco, habdles el caso de que no entre paréntesis estar presente, y los errores si ha desequilibrado errores. He dejado en la depuración de las declaraciones, de modo que usted puede activarlos para ver lo que está sucediendo.

Option Explicit

Public Sub ttest()

    Dim myRange As Word.Range
    Set myRange = ActiveDocument.StoryRanges(wdMainTextStory)
    myRange.Collapse direction:=wdCollapseStart
    
    
    Set myRange = NextParenRange(myRange)
    
    Do Until myRange Is Nothing
    
        DoEvents
        
        Debug.Print myRange.Text
        Dim myDupRange As Word.Range
        Set myDupRange = myRange.Duplicate
        myRange.Collapse direction:=wdCollapseEnd
        If myDupRange.Characters.Last.Next.Text = " " Then myDupRange.MoveEnd Count:=1
        myDupRange.Delete
        Set myRange = NextParenRange(myRange)
        
    
    Loop
    
End Sub

Public Function NextParenRange(ByVal ipRange As Word.Range) As Word.Range

    Const OpenP As String = "("
    Const CloseP As String = ")"
    
    Dim myRange As Word.Range
    Set myRange = ipRange.Duplicate
    
    'If myRange.Start <> myRange.End Then myRange.Collapse direction:=wdCollapseStart
    
    'exit if no parentheses exist
    'Debug.Print myRange.Start
    If myRange.MoveUntil(cset:=OpenP) = 0 Then
    
        Set NextParenRange = Nothing
        Exit Function
        
        
    Else
    
        'Debug.Print myRange.Start
        Dim myParenCount As Long
        myParenCount = 1
        myRange.MoveEnd Count:=1

    End If
    
    
    Do Until myParenCount = 0
    
        ' allows VBA to respond to a break key press
        DoEvents
        
        ' if we run out of parentheses before we get back to zero then flag an error
        If myRange.MoveEndUntil(cset:=OpenP & CloseP) = 0 Then
        
            VBA.Err.Raise 17, "Unbalanced parentheses in document"
            
            
        End If
        
        myRange.MoveEnd Count:=1
        'Debug.Print myRange.Characters.Last.Text
        'Debug.Print myRange.Characters.Last.Next.Text
        myParenCount = myParenCount + IIf(myRange.Characters.Last.Text = OpenP, 1, -1)
        
    
    Loop
    
    Set NextParenRange = myRange.Duplicate
    
End Function
2021-11-21 14:57:37

solución agradable (y)
Brett

Bastante limpio, gracias!
user1357015

@freeflow: Alguna sugerencia de cómo cambiar el código para que funcione con una selección específica sólo? He cambiado Set myRange = Selection.StoryRanges(wdMainTextStory) pero eso no parece suficiente.
user1357015

Usted tendrá que hacer dos cosas. El cambio de " Set myRange = ActiveDocument.StoryRanges(wdMainTextStory)' a 'Establecer myRange=selección.La gama'. Usted también tendrá que capturar el final de myrange en una nueva variable y, a continuación, en el bucle do until prueba de que el actual inicio de la gama no es más que la salvó de la gama. por ejemplo, algo como '¿hasta myRange.inicio>=mySavedEnd'
freeflow

En otros idiomas

Esta página está en otros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Slovenský
..................................................................................................................