I'm having trouble using regular expressions in Google Docs to delete periods at the end of every line.
I tried importing the text into Microsoft Word but I don't know how to make the macro. All I have is this code:
Sub doRegexFindReplace()
Dim objRegex As RegExp
Dim matches As MatchCollection
Dim fnd As Match
Dim strSample As String
strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45."
Set objRegex = New RegExp
With objRegex
.Pattern = "(fox) (\d+)"
.Global = True
.IgnoreCase = True
strSample = .Replace(strSample, "$1$2")
End With
Debug.Print strSample
End Sub
It might be too complex to figure out. That's ok if it is.
The regex for a trailing period would be \.$ Now I don’t know if that will work in Google Docs. The \ is the escaping character, which you need because in the RegEx world . is a reserved keyword. The $ means end of line.
Related
I am stuck - I feel I have checked everything multiple times but I need some pair of fresh eyes on this one:
Sub shopNumConvert()
Call settings
Dim SearchString As String
Dim ReplaceString As String
Dim InputString As String
Dim ShopRange As Range
'Dim RegEx As New RegExp
Dim RegEx As RegExp
SearchString = "[^a-z]{2}"
ReplaceString = "0\\1"
Set ShopRange = DataWs.Range("G2:G10")
Set RegEx = New RegExp
For Each cell In ShopRange
If SearchString <> "" Then
InputString = cell.Value
With RegEx
.Global = True
.IgnoreCase = False
.MultiLine = True
.Pattern = SearchString
End With
If RegEx.Test(InputString) Then
ShopRange.Value = (RegEx.Replace(InputString, ReplaceString))
End If
End If
Next
Set RegEx = Nothing
End Sub
Why do I get the error message Object variable or With block variable not set
In settings() I have defined which sheet 'DataWs' is
Help is much appreciated!
Thank you for your comments (and good practice advise - not working with VBA frequently so I am learning on the go)!
The problem was indeed with DataWs and I had to change something in settings() - the code as posted now runs without throwing an error - I will however look at a few of your comments and see how to incorporate those for improving the code.
Best,
Janine
I get assignments in emails that come to a shared Outlook mailbox.
In a typical email there are multiple strings and variables regarding a client, including their name, date and ID with a hyphen that I also want to get rid of.
There are two types of IDs. Both consist of 8 numbers and a hyphen, e.g. 1234567-8 and 123456-78. Sometimes there is a character in front of the number so I believe storing data in string is a must. I want to make several copies of the macro for each type of data. I want it all in a simple string form as I want to copy it to clipboard and paste elsewhere and have no need to process it further.
The code below does all I want except it stores the data in variables instead of string and does not remove the hyphen.
Code courtesy of vbaexpress' gmayor.
Option Explicit
Sub GetCustomer()
Dim olItem As Outlook.MailItem
Dim olInsp As Outlook.Inspector
Dim dCust As DataObject
Dim wdDoc As Object
Dim oRng As Object
Dim sCustomer As String
Dim bFound As Boolean
On Error GoTo lbl_Exit
Set olItem = ActiveExplorer.Selection.Item(1)
With olItem
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
Set oRng = wdDoc.Range
With oRng.Find
Do While .Execute(findText:="Customer #:[ 0-9]{2,}", MatchWildcards:=True)
sCustomer = Trim(Split(oRng.Text, Chr(58))(1))
bFound = True
Set dCust = New DataObject
dCust.SetText sCustomer
dCust.PutInClipboard
MsgBox "Customer number '" & sCustomer & "' copied to clipboard"
Exit Do
Loop
End With
If Not bFound Then MsgBox "Customer number not found"
End With
lbl_Exit:
Set olItem = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set oRng = Nothing
Set dCust = Nothing
Exit Sub
End Sub
I want to search the currently previewed email (if that is possible), without actually opening it in another separate window, for a phrase like
"Customer ID: 123456-78"
and reformat the last part by simply removing the hyphen and disregarding the first part
"Customer ID: "
(there is a giant space between the Customer ID and the number).
I also want to reformat the date from 11.22.2019 to 2019-22-11 and also copy it to clipboard.
Searches based on wildcards are limited to what wildcards can provide, which is better than nothing, but still not very much.
Outlook uses Word functions for this, so that the VBA documentation for Word applies. Applicable wildcards themselves are can be seen using the "Special" button in the "Find" dialog (F4 in Outlook), after "use wildcards" has been checked.
To my knowledge there is no concept of "optional" parts in wildcard searches, which means you need to try more than one wildcard pattern to cover your "sometimes there is a letter in front" case.
So the general approach, based this knowledge and on your sample code, would be
Pick the currently selected MailItem in the ActiveExplorer
For each predefined wildcard pattern
reset the search range to the whole email
execute wildcard search
as long as there are search hits
display result, let user pick or cancel the search
This way multiple patterns can be defined and you have a chance to continue to the next hit if the first hit is a false positive.
I found the pattern [0-9-]{8;9} plus MatchWholeWord to work reasonably well (blocks of digits and dashes, between 8 or 9 characters long), but real life data often has surprises. You will probably need to add more patterns. Watch out: for me, Outlook wants ; instead of ,. This might be dependent on the system locale, I'm not sure.
Also I'm not a fan of a "silent" On Error Resume. If there is an error, I prefer to see an error actual message. If there is a condition that can be checked in order to prevent an error, I prefer to check for this condition explicitly. This makes the code more robust and debugging easier. My Sub does not contain an On Error line for that reason.
In code, this would look like this:
Sub GetCustomer()
Dim olItem As Outlook.MailItem
Dim oRng As Object
Dim sCustomer As String
Dim patterns As Variant, pattern As Variant
Dim answer As VbMsgBoxResult
' bail out if the preconditions are not right
If ActiveExplorer.Selection.Count = 0 Then Exit Sub
If Not (TypeOf ActiveExplorer.Selection.item(1) Is MailItem) Then Exit Sub
Set olItem = ActiveExplorer.Selection.item(1)
Set oRng = olItem.GetInspector.WordEditor.Range
' add more wildcard patterns in descending order of likelyhood
patterns = Array("[0-9-]{8;9}", "[A-Z][0-9-]{8;9}")
For Each pattern In patterns
oRng.WholeStory
While oRng.Find.Execute(findText:=pattern, MatchWildcards:=True, MatchWholeWord:=True)
answer = MsgBox(oRng.Text, vbYesNoCancel + vbQuestion, "Customer Number")
If answer = vbYes Then
With New DataObject
.SetText oRng.Text
.PutInClipboard
End With
Exit For
ElseIf answer = vbCancel Then
Exit For
End If
Wend
Next pattern
End Sub
Setting variables to Nothing at the end of the function is superfluous.
My code:
Public Sub splitUpRegexPattern()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("B2:B4279")
For Each c In Myrange
strPattern = "([A-Z]{2}\/[A-Z]{2}\/[A-Z][0-9]{2}\/[a-z]{3}[0-9]{9}\/)([0-9]{4})"
If strPattern <> "" Then
strInput = c.Value
strReplace = "$1"
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
c.Offset(0, 1) = regEx.Replace(strInput, "$2")
Else
c.Offset(0, 1) = ""
End If
End If
Next
End Sub
It was initially working well, it would give me an error, but still complete the task it was doing. But when I use this macro on a new spreadsheet, it gives me the error:
Compile Error: Method or Data Member not found.
All the solutions on this site are tailored to different situations, so I couldn't apply them to my circumstance unfortunately.
I have no idea why this is happening, as I haven't changed any of the code. I am sure if I had a greater understanding with VBA script that I would be able to understand this, but I do not, so I came to find out if someone here could help me!
Thanks!
Aydan
You need to add a reference to a library called "Microsoft VBScript Regular Expressions 5.5" to make it work.
If this code works in a workbook that simply means you have added that library reference and when you copy the code to a new workbook there you will need to add the same reference again.
In the existing code you are auto instantiating the variable called redEx which assumes that the library reference has been already added to make it work properly.
To avoid this, you may use the late binding technique which will not require you to add the reference and the code will work on any workbook.
To do so declare the regEx variable as an Object like below...
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
My best guess is that you've lost a reference to a library. In VBE, select Tools - References. Find Microsoft VBScript Regular Expressions 5.5 and tick it.
I have a excel workbook with multiple sheets, each having multiple cells containing HTML text. How can I convert this text directly to regular text with all the formatting defined in HTML tags. Is it possible to have a macro which can scan all such cells and convert them at once?
try the below function to strip all the html tags (except Bold and break) and to get regular text by parsing the html text to this function like striphtml(your html text).
Function StripHTML(sInput As String) As String
Dim RegEx As Object
Set RegEx = CreateObject("vbscript.regexp")
Dim sOut As String
With RegEx
.Global = True
.IgnoreCase = True
.MultiLine = True
.Pattern = "<(?!/?(?:br|b)\b)[^>]*>" 'Regular Expression for HTML Tags.
End With
sOut = RegEx.Replace(sInput, "")
StripHTML = sOut
Set RegEx = Nothing
End Function
I'm a third year software design student. I'm currently in the middle of my work placement. I had been asked to create a tool to parse word documents for relevant tabular data and export it to ms excel. I had never had any dealings with VB but based on the research I carried out I decided that was the route to take. Anyway I managed to execute this successfully. Now, however, I have been asked to expand the program to parse paragraphs also. The documents are broken down into chapters. Each chapter heading is in 'h2' style, my idea is to try to search all text in 'h2' style for a unique string and if found, which should be the required heading, then process the text underneath.
Can this be done?? If so, can you please let me know how, this has been a steep learning curve, and I was delighted with what I had achieved, now, I'm stuck dead. I have the methodology, it's finding the correct way to implement it. This will also allow me to create a search form which I intend to integrate to allow the user search for the chapter they want to parse...
If anyone can help me get out of this hole I would greatly appreciate it.
Take your Pick
VBA WORD CODE (Place this in a module)
Option Explicit
Sub VBASample()
Dim para As Paragraph
Dim strParaText As String
Dim searchString As String
searchString = "Sample"
For Each para In ActiveDocument.Paragraphs
If para.Style = "Heading 2" Then
strParaText = para.Range.Text
If InStr(1, strParaText, searchString, vbTextCompare) Then
'~~> You code here if the text is found
MsgBox "Found"
End If
End If
Next para
End Sub
VB6 CODE
Option Explicit
'~~> Using Late Binding so no reference to Word object is required.
Sub VB6Sample()
Dim oWordApp As Object, oWordDoc As Object, oWordPara As Object
Dim FlName As String, strParaText As String, searchString As String
'~> File Name where you want to check the paragraphs
FlName = "C:\Documents and Settings\Siddharth Rout\Desktop\Sample.doc"
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
'~~> String that you want to search
searchString = "Sample"
For Each oWordPara In oWordDoc.Paragraphs
If oWordPara.Style = "Heading 2" Then
strParaText = oWordPara.Range.Text
If InStr(1, strParaText, searchString, vbTextCompare) Then
'~~> You code here if the text is found
MsgBox "Found"
End If
End If
Next oWordPara
End Sub