I've been trying to count how many open brackets "(" and close brackets ")" I have in my selection and fire other subs accordingly. I've been using the following code:
Public Sub DEVAuti()
Dim iCountA, iCountB, iCountSA, iCountSB As Long
Dim strSearchA, strSearchB As String
strSearchA = "("
iCountA = 0
strSearchB = ")"
iCountB = 0
Set Range = ActiveDocument.Range(Selection.Range.Start, Selection.Range.End)
Set RangeStart = ActiveDocument.Range(Selection.Range.Start, Selection.Range.Start 999)
Set RangeEnd = ActiveDocument.Range(Selection.Range.End, Selection.Range.End 999)
iCountLine = Selection.Range.ComputeStatistics(wdStatisticLines)
With RangeStart.Find
.Text = strSearchA
.Format = False
.Wrap = wdFindStop
Do While .Execute
iCountA = iCountA 1
Loop
End With
With RangeEnd.Find
.Text = strSearchA
.Format = False
.Wrap = wdFindStop
Do While .Execute
iCountB = iCountB 1
Loop
End With
iCountSA = iCountA - iCountB
iCountA = 0
iCountB = 0
With RangeStart.Find
.Text = strSearchB
.Format = False
.Wrap = wdFindStop
Do While .Execute
iCountA = iCountA 1
Loop
End With
With RangeEnd.Find
.Text = strSearchB
.Format = False
.Wrap = wdFindStop
Do While .Execute
iCountB = iCountB 1
Loop
End With
iCountSB = iCountA - iCountB
End Sub
Since it starts counting outside the selection I tried working with two ranges (basically one is from the start of selection until the end of the document and the other is from the end of the selection until the end of the document) but it's starting to get messy and not count properly.
Whats an easier way to do this?
CodePudding user response:
For example:
Sub Test()
Dim StrTxt As String, x As Long, y As Long, z As Long
StrTxt = Selection.Text
x = Len(StrTxt)
y = Len(Replace(StrTxt, "(", ""))
z = Len(Replace(StrTxt, ")", ""))
MsgBox "There are:" & vbCr & _
Chr(149) & " " & x - y & " opening parens; and" & vbCr & _
Chr(149) & " " & x - z & " closing parens," & vbCr & _
"in the selection."
End Sub
CodePudding user response:
You could use a formula, and go from there?
To get Open Parenthesis (assuming data is in A1
):
=(LEN(A1)-LEN(SUBSTITUTE(A1,"(","")))
To get the closed parenthesis count, change above to a closed parenthesis in SUBSTITUTE()
.
If you want to count both open and closed:
=(LEN(A1)-LEN(SUBSTITUTE(SUBSTITUTE(A1,"(",""),")","")))