Call/Argument Error with Asc() - Delete "unnecessary" lines in MSWord 2007 - vba

Final Update: It has been resolved in an answer below. Thanks!
Probelm has been NOT been resolved :-(. The script does not interact well with MSword Fields.
Goal: Delete lines in MSWord 2007 that contain any number of spaces, tabs, and the obvious pilcrow (paragraph mark).
Steps Taken: I googled it and found this forum.
I then found this in a samble of a book on google and tried to modify it.
The modified is below:
Dim oPara As Word.Paragraph
Dim var
Dim SpaceTabCounter As Long
Dim oChar As Word.Characters
For Each oPara In ActiveDocument.Paragraphs
If Len(oPara.Range) = 1 Then
oPara.Range.Delete
Else
SpaceTabCounter = 0
Set oChar = oPara.Range.Characters
For var = 1 To oChar.Count
Select Case Asc(oChar(var)) ' ' ' ' 'ERROR is here
Case 32, 9
SpaceTabCounter = SpaceTabCounter + 1
End Select
Next
If SpaceTabCounter + 1 = Len(oPara.Range) Then
' paragraph contains ONLY spaces
oPara.Range.Delete
End If
End If
Next
The issue is that I get an error at "Select Case Asc(oChar(var))" half way down the code.
"Run-time error '5': Invalid procedure call or argument"
I'm new to VBA and...I can't figure this out. Please send your love!
Thanks
The error is still occuring.
Code as it stands now:
Dim oPara As Word.Paragraph
Dim var
Dim SpaceTabCounter As Long
Dim oChar As Word.Characters
For Each oPara In ActiveDocument.Paragraphs
If Len(oPara.Range) = 1 Then
oPara.Range.Delete
Else
SpaceTabCounter = 0
Set oChar = oPara.Range.Characters
For var = 1 To oChar.Count
Select Case Asc(oChar(var).Text) 'modified this line: added ".Text"
Case 32, 9
SpaceTabCounter = SpaceTabCounter + 1
End Select
Next
If SpaceTabCounter + 1 = Len(oPara.Range) Then
' paragraph contains ONLY spaces
oPara.Range.Delete
End If
End If
Next

When your code comes across a content control field, it reads the first character in the paragraph as an empty string. This behavior can be observed by checking the oChar.First.Text field in the local variables window. Asc() will throw an error when passed an empty string. This can be easily reproduced by running this procedure.
Sub throwError5()
Debug.Print Asc("")
End Sub
You will need to test the value of oChar(var) to ensure it is not an empty string prior to returning its ASCII value.
Option Explicit
Sub deleteEmptyParagraphs()
Dim oPara As Word.Paragraph
Dim var
Dim SpaceTabCounter As Long
Dim oChar As Word.Characters
For Each oPara In ActiveDocument.Paragraphs
If Len(oPara.Range) = 1 Then
oPara.Range.Delete
Else
SpaceTabCounter = 0
Set oChar = oPara.Range.Characters
For var = 1 To oChar.Count
If oChar(var) <> "" Then ' stops Asc from throwing runtime error 5
Select Case Asc(oChar(var)) ' no more errrors!
Case 32, 9
SpaceTabCounter = SpaceTabCounter + 1
End Select
End If
Next
If SpaceTabCounter + 1 = Len(oPara.Range) Then
' paragraph contains ONLY spaces
oPara.Range.Delete
End If
End If
Next
End Sub
I don't work with the Word object model often, so I have no idea why the fields' first character is an empty string. Please note that my comment about having to call oChar(index).Text was wrong. Text is the default property of a characters item.

Related

Excel VBA - Copy first set of characters in ActiveCell before space

Here's what I have so far. Immediate window shows the result I want, but Clipboard remains without that result. I want those characters on the Clipboard.
Sub CopyFirst()
Dim position As Integer
Dim substring As String
position = InStr(ActiveCell, " ")
If (position > 0) Then
substring = Left(ActiveCell, position - 1)
Debug.Print substring
End If
End Sub
To avoid early binding:
Sub CopyFirst()
Dim position As Integer
Dim substring As String
Dim MSForms_DataObject As Object
Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
position = InStr(ActiveCell, " ")
If (position > 0) Then
substring = Left(ActiveCell, position - 1)
End If
MSForms_DataObject.setText substring
MSForms_DataObject.PutInClipboard
Set MSForms_DataObject = Nothing
End Sub
There's nothing in your code that touches the clipboard yet. Add a reference to Microsoft Forms 2.0 library if you don't have it yet.
Sub CopyFirst()
Dim position As Integer
Dim substring As String
position = InStr(ActiveCell, " ")
If (position > 0) Then
substring = Left(ActiveCell, position - 1)
Dim MyText As DataObject
Set MyText = New DataObject
On Error Resume Next
MyText.setText substring
MyText.PutInClipboard
End If
End Sub

How to skip or ignore find tables MS Word?

I've a macro code (created by Davy C) to find paragraph styles and add comment for each one if found. I need to improve this code. I want to run this macro code only paragraphs and need to skip/ignore tables when found. How do I do this?
Sub CheckKeepWithNext01()
Const message As String = "Check Keep With Next"
Const styleMask As String = "Bold + KWN"
Dim paragraphCount As Integer
Dim i As Integer
Dim currentStyle As String
Dim doc As Document
Set doc = ActiveDocument
paragraphCount = doc.Paragraphs.count
Do While i < paragraphCount
i = i + 1
If doc.Paragraphs(i).Range.Bold = True Then
If doc.Paragraphs(i).KeepWithNext = False Then
currentStyle = doc.Paragraphs(i).Range.Style
If Left(currentStyle, Len(styleMask)) <> styleMask Then
doc.Paragraphs(i).Range.Select
Selection.Comments.Add Range:=Selection.Range
Selection.TypeText Text:=message
End If
End If
End If
Loop
Set doc = Nothing
End Sub
See below screenshot for more clarity:
I've got the answer!
If doc.Paragraphs(i).Range.Tables.count = 0 Then

Finding a certain character in Visio and reformating the following text

Due to a tight timing for one of my projects with Visio I need to look over all the shapes in All the pages for certain character (name it "&") and then change the color of n character after it, so i wrote a code like follow but it does not go through all occurrences in one text block, after it hits the first one the loop exits... I just need help to resolve it my mind is kind of frozen now... sorry if my question is silly
Sub test()
Dim PageObj As Visio.Page
Dim shpsObj As Visio.Shapes
Dim shpObj As Visio.Shape
Dim oShpChar As Visio.Characters
Set PageObj = ActivePage
Set shpsObj = PageObj.Shapes
For Each shpObj In shpsObj
'Dim iLength As Integer
Dim iBeginOffset As Integer, iEndOffset As Integer
Set oShpChar = shpObj.Characters
Do
iBeginOffset = InStr(oShpChar.Text, "&test")
'If iBeginOffset = 0 Then Exit Do ' # Not found -> end the loop
iEndOffset = iBeginOffset + 3
oShpChar.Begin = iBeginOffset
oShpChar.End = iEndOffset
oShpChar.CharProps(visCharacterColor) = 9
oShpChar.Begin = oShpChar.Begin + 1
oShpChar.End = oShpChar.CharCount
Loop While (iEndOffset < oShpChar.CharCount)
Next
End Sub
I just tagged it for Excel too since the overall concept is the same...
The problem is found...
Unfortunately Microsoft Visio does not hold the updated value for "Character.Begin" and "Character.End" properties through outer loop, in other word it maintained but not accessible by other method such as"CharProps". so I introduced a counter outside of while loop to keep track of each new value for the mentioned property, hope it helps others to resolve their issue too, it's cost me 7 hours
(I am not a developer so please correct me if I made a mistake in my explanations)!
Sub test()
Set PageObj = ActivePage
Set shpsObj = PageObj.Shapes
For Each shpObj In shpsObj
Dim searchWord As String
Dim placeHolder As Integer
Dim iLength As Integer
Dim iBeginOffset As Integer, iEndOffset As Integer
Set oShpChar = shpObj.Characters
searchWord = "&test"
iLength = oShpChar.CharCount
Do
iBeginOffset = InStr(oShpChar.Text, searchWord)
If iBeginOffset = 0 Then Exit Do ' searchWord Not found -> end the loop
iBeginOffset = iBeginOffset + placeHolder
placeHolder = iBeginOffset + Len(searchWord) - 1
iEndOffset = iBeginOffset + Len(searchWord) - 1
oShpChar.Begin = iBeginOffset
oShpChar.End = iEndOffset
If iEndOffset > iLength Then Exit Do ' Preventing the last run
oShpChar.CharProps(visCharacterColor) = 9
oShpChar.Begin = oShpChar.Begin + Len(searchWord) - 1
oShpChar.End = iLength
Loop While (iEndOffset < iLength)
Next
End Sub

How to remove vb.net Richtextbox lines that not contains specific text?

I use the next code to remove lines from Richtextboxes but that way i can only tell what line to remove. I need to remove all lines that not contains specific text, can this be done with some edits of my code?
1st piece:
Private Property lineToBeRemovedlineToBeRemoved As Integer
2nd piece:
Dim lineToBeRemoved As Integer = 0
lineToBeRemovedlineToBeRemoved = lineToBeRemoved - 0
Dim str As String = RichTextBox1.Lines(lineToBeRemoved)
RichTextBox1.Find(str & vbCr)
RichTextBox1.SelectedText = ""
This code will remove any line from a richtextbox RichTextbox1 that does not contain "Test" on it. Remember to add Imports System.Text.RegularExpressions to the top of your code.
Private Sub RemoveLines()
Dim lines As New List(Of String)
lines = RichTextBox1.Lines.ToList
Dim FilterText = "Test"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
RichTextBox1.Lines = lines.ToArray
End Sub
You code is not close. You should start over. Use a for loop to go through the RichTextBox lines. If the text is not in a line, then delete it. Tip: It may be easier to go from the last line to the first to avoid problems when deleting.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RTB.Select(RTB.GetFirstCharIndexFromLine(2), RTB.Lines(2).Count)
RTB.SelectionLength = RTB.Lines(2).Length + 1
RTB.SelectedText = ""
End Sub
Try this code, I applied to my prog and it work good.
When use, just ... call dels("unwanted") ==> Line which contain unwanted word will disappear.
Private Sub dels(sw As String)
Dim ud As String = "" 'for keep all we need
Dim cn As Integer = 0 'for avoid empty line
For Each line As String In RichTextBox1.Lines 'for every line in reichtextbox
If Len(line) > 5 Then 'if that line got more than 5 character
If InStr(line.ToLower, sw.ToLower) < 1 Then 'transform them to lower case for better resulted
If cn = 1 Then ud = ud + vbCrLf 'not place new-line if it is first
ud = ud + line 'keep this line if not match ne want delete
cn = 1 'turn-off first line signal
End If
End If
Next
RichTextBox1.Clear() 'empty richtextbox
RichTextBox1.AppendText(ud) 'update richtextbox with the unwanted
End Sub

What is causing 'Index was outside the bounds of the array' error?

What is causing 'Index was outside the bounds of the array' error? It can't be my file, defianetly not. Below is my code:
Sub pupiltest()
Dim exitt As String = Console.ReadLine
Do
If IsNumeric(exitt) Then
Exit Do
Else
'error message
End If
Loop
Select Case exitt
Case 1
Case 2
Case 3
End Select
Do
If exitt = 1 Then
pupilmenu()
ElseIf exitt = 3 Then
Exit Do
End If
Loop
Dim score As Integer
Dim word As String
Dim totalscore As Integer = 0
'If DatePart(DateInterval.Weekday, Today) = 5 Then
'Else
' Console.WriteLine("You are only allowed to take the test on Friday unless you missed it")
' pupiltest()
'End If
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Dim stdntfname As String = founditem(3)
Dim stdntsname As String = founditem(4)
Dim stdntyear As String = founditem(5)
Console.Clear()
If founditem IsNot Nothing Then
Do
If stdntyear = founditem(5) And daytoday = founditem(6) Then
Exit Do
ElseIf daytoday <> founditem(6) Then
Console.WriteLine("Sorry you are not allowed to do this test today. Test available on " & item(6).Substring(0, 3) & "/" & item(6).Substring(3, 6) & "/" & item(6).Substring(6, 9))
Threading.Thread.Sleep(2500)
pupiltest()
ElseIf stdntyear <> founditem(5) Then
Console.WriteLine("Year not found, please contact the system analysts")
Threading.Thread.Sleep(2500)
pupiltest()
End If
Loop
End If
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\testtests.csv")
Dim item() As String = line.Split(","c)
Dim mine As String = String.Join(",", item(2), item(3), item(4), item(5), item(6))
For i As Integer = 1 To 10
Console.WriteLine(i.ToString & "." & item(1))
Console.Write("Please enter the word: ")
word = Console.ReadLine
If word = Nothing Or word <> item(0) Then
score += 0
ElseIf word = item(0) Then
score += 2
ElseIf word = mine Then
score += 1
End If
Next
If score > 15 Then
Console.WriteLine("Well done! Your score is" & score & "/20")
ElseIf score > 10 Then
Console.WriteLine("Your score is" & score & "/20")
ElseIf score Then
End If
Next
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdntscores", True)
sw.Write(stdntfname, stdntsname, stdntyear, score, daytoday, item(7))
Try
Catch ex As Exception
MsgBox("Error accessing designated file")
End Try
End Using
End
End Sub
All help is highly appreciated,
You are constantly replacing the foundItem array when you do founditem = item:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.
Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then
Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then
Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array
So when you try to do the following later, it throws the exception.
Dim stdntfname As String = founditem(3) 'index 3 does not exist!
To fix it do the following change:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
'NOTE: Make sure you know exactly how many columns your csv has or whatever column
' you wish to access.
Dim item() As String = line.Split(","c)
founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
founditem(1) = item(1)
founditem(2) = item(2)
founditem(3) = item(3)
founditem(4) = item(4)
founditem(5) = item(5)
founditem(6) = item(6)
Next
For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet
In your line Dim item() As String = line.Split(","c) there's no guarantee that the correct number of elements exist. It's possible that one of the lines is missing a comma or is a blank trailing line in the document. You might want to add a If item.Length >= 7 and skipping rows that don't have the right number of rows. Also, remember that unlike VB6, arrays in .Net are 0 based not 1 based so make sure that item(6) is the value that you think it is.