PDA

View Full Version : Find and replace if specific conditions aply



Omeva
05-08-2023, 11:07 AM
I need help for checking citations. I have to check long documents if "cf." Is used correctly. I either need a way to highlight the brackets or sentences in which "cf." Is used or for the VBA to do it itself.
If there is a "." Or any word in front of the bracket it needs "cf.". If there are quotation marks in front of the bracket there should be no "cf."
For example this is correct:
example. (cf. Weber 2010)
Example (cf. Weber 2010)
This is incorrect:
Example" (cf. Weber 2010)
Example. (Weber 2010)


I tried something to highlight sentences with quotation marks, but it is not doing what I want, please help : pray2:


Sub CheckParentheses()
' CheckParentheses Makro
Dim paragraph As paragraph
Dim Doc As Document
' Set the document object to the active document
Set Doc = ActiveDocument
' Loop through all paragraphs in the document
For Each paragraph In Doc.Paragraphs
' Check if the paragraph has the "Standard" style and does not contain a parenthesis
If paragraph.Style = "Standard" And InStr(paragraph.Range.Text, "(") = 0 And InStr(paragraph.Range.Text, ")") = 0 Then
' Highlight the paragraph in yellow
paragraph.Range.HighlightColorIndex = wdYellow
End If
Next
End Sub

gmayor
05-09-2023, 05:01 AM
Why not just fix the errant references e.g.


Sub Macro1()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
Do While .Execute(findText:="? \(", MatchWildcards:=True)
With oRng
.End = .End + 4
If .Characters(1).Text = Chr(34) Then
.Text = Replace(.Text, "cf. ", "")
.Paragraphs(1).Range.HighlightColorIndex = wdYellow
Else
If InStr(1, .Text, "cf. ") = 0 Then
.End = .End - 4
.InsertAfter "cf. "
.Paragraphs(1).Range.HighlightColorIndex = wdYellow
End If
End If
.Collapse 0
End With
Loop
End With
End Sub

Omeva
05-09-2023, 06:25 AM
Hi,
Thank you for your reply. The macro does something, but it changes all instances. If there are quotation marks before the bracket I don't want the macro to add cf.


Why not just fix the errant references e.g.


Sub Macro1()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
Do While .Execute(findText:="? \(", MatchWildcards:=True)
With oRng
.End = .End + 4
If .Characters(1).Text = Chr(34) Then
.Text = Replace(.Text, "cf. ", "")
.Paragraphs(1).Range.HighlightColorIndex = wdYellow
Else
If InStr(1, .Text, "cf. ") = 0 Then
.End = .End - 4
.InsertAfter "cf. "
.Paragraphs(1).Range.HighlightColorIndex = wdYellow
End If
End If
.Collapse 0
End With
Loop
End With
End Sub

gmayor
05-09-2023, 09:44 AM
If your examples accurately reflect what is in the document then cf is not added, but removed if present. Post a sample document..