VB6 - How to list PIDs related to Usernames - list

I am still very new to VB6 and VB Studio.
I want to get a list of all the Process ID's and the Usernames associated with those ID's
I am not using a form, as no GUI will be needed, but for testing purposes, I would like to output the list to a msgbox or notepad file.
This is what I have got so far, but it does not run in VB Studio. It does work as a VBS, but will not save as an exe with the error "Invalid Outside Procedure"
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strList
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process")
For Each objProcess in colProcess
strList = strList & vbCr & _
objProcess.Name
Next
WSCript.Echo strList
WScript.Quit
Any help is appreciated

Add a Module to your project and use the code below. It writes the data out to a text file in the temp folder. From the Project>Properties menu make sure the "Startup Object" is Sub Main.
Option Explicit
Dim objWMIService As Object
Dim objProcess As Object
Dim colProcess As Object
Dim strComputer As String
Dim strUserName
Dim strUserDomain
Sub Main()
On Error GoTo eh
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery("Select * from Win32_Process")
Open "c:\temp\test.txt" For Output As #1
For Each objProcess In colProcess
objProcess.GetOwner strUserName, strUserDomain
Print #1, objProcess.Name & vbTab & strUserName
Next
Close #1
MsgBox ("Done")
Exit Sub
eh:
MsgBox (Error$)
End Sub

Related

Loop through validation list and print pdf to a folder defined by a cell

I used an answer from a similar question to get the vba below. This vba script works when the folderpath is hardcoded but I am hoping to have the folder for the printed pdf file be definde by a cell ("G7").
Sub Loop_Through_List()
Sheets("Report Template").Select
Range("B5").Select
Dim ws As Worksheet
Dim cell As Excel.Range
Dim rgDV As Excel.Range
Dim DV_Cell As Excel.Range
Dim folderPath As String
folderPath = GetFolder(Range("G7").Value)
'folderPath = GetFolder()
Set DV_Cell = Range("B5")
Set rgDV = Application.Range(Mid$(DV_Cell.Validation.Formula1, 2))
For Each cell In rgDV.Cells
DV_Cell.Value = cell.Value
PDFActiveSheet folderPath
Next
Sheets("Notes").Select
Range("A1").Select
End Sub
Sub PDFActiveSheet(Optional ByVal folderPath As String = "")
Dim ws As Worksheet
Dim myFile As Variant
Dim strFile As String
Dim sFolder As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = ws.Range("B5").Value
If folderPath = "" Then
'--- if no folder path is specified, then default to
' the same path as the active workbook
folderPath = ActiveWorkbook.Path
If Len(folderPath) = 0 Then
'--- to force Excel to have a path (instead of no
' path at all), use the current directory
' notation
folderPath = "."
End If
End If
myFile = folderPath & "\" & strFile
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False, _
From:=1, _
To:=2
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Function GetFolder() As String
Dim dlg As FileDialog
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
dlg.InitialFileName = ThisWorkbook.Path & "\"
dlg.Title = "Select folder to save PDFs"
If dlg.Show = -1 Then
GetFolder = dlg.SelectedItems(1)
End If
End Function
If the folder name is already in cell G7, you don't need the GetFolder function:
Current code
folderPath = GetFolder(Range("G7").Value)
Replace with:
folderPath = Range("G7").Value
I was able to get it working with Mike's help. In the end, I used ActiveWorkbook.Path & "" to define the folderpath. I don't know if any of the code is redundant but it works for what I need. Thank you very much.
Sub Loop_Through_List()
Sheets("Report Template").Select
Range("B5").Select
Dim ws As Worksheet
Dim cell As Excel.Range
Dim rgDV As Excel.Range
Dim DV_Cell As Excel.Range
Dim folderPath As String
Dim Path As String
folderPath = ActiveWorkbook.Path & "\"
'folderPath = GetFolder()
Set DV_Cell = Range("B5")
Set rgDV = Application.Range(Mid$(DV_Cell.Validation.Formula1, 2))
For Each cell In rgDV.Cells
DV_Cell.Value = cell.Value
PDFActiveSheet folderPath
Next
Sheets("Notes").Select
Range("A1").Select
End Sub
Sub PDFActiveSheet(Optional ByVal folderPath As String = "")
Dim ws As Worksheet
Dim myFile As Variant
Dim strFile As String
Dim sFolder As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = ws.Range("B5").Value
If folderPath = "" Then
'--- if no folder path is specified, then default to
' the same path as the active workbook
folderPath = ActiveWorkbook.Path
If Len(folderPath) = 0 Then
'--- to force Excel to have a path (instead of no
' path at all), use the current directory
' notation
folderPath = "."
End If
End If
myFile = folderPath & "\" & strFile
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False, _
From:=1, _
To:=2
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Function GetFolder() As String
Dim dlg As FileDialog
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
dlg.InitialFileName = ThisWorkbook.Path & "\"
dlg.Title = "Select folder to save PDFs"
If dlg.Show = -1 Then
GetFolder = dlg.SelectedItems(1)
End If
End Function

Structure replacement possible complex RegexReplace solution?

I need to run a VBScript that changes the structure of a CSV file. To keep it simple I'm only using 3 data fields but there is a lot more. In a production environment I will have a CSV file with hundreds of lines.
The problem is everything is in double quotes. The end result can sometimes be no quotes or single quotes or sometimes a mix of all three.
I have absolutely no idea how I should approach this and was looking for some guidance. This looks like a job for RegexReplace but because it's mixed I'm not sure how to start this. After the file has been modified I have to right over top of the original file.
CSV Example:
"apple";"12";"xyz"
"somereallylongword";"7687";"theredfox"
Pattern
"%1";%2;'%3'
Desired Result
"apple";12;'xyz'
"somereallylongword";7687;'theredfox'
What I'm trying to achieve is to be able to make a new pattern type.  In my example:
"%1" - I keep the original double quotes.
%2 - Remove the double quotes.
'%3' - Replace the double quotes with single quotes.
Any insight would be greatly appreciated.
You can read the CSV file using ADODB:
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim objConnection
Dim objRecordset
Dim sCSVFolder
Dim sCSVFile
Dim sValue
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
sCSVFolder = "C:\CSV_Folder\"
sCSVFile = "your_csv_file.csv"
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sCSVFolder & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM " & sCSVFile, _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
' Modify and write fields to new text file here
sValue = objRecordset.Fields.Item("FieldName")
objRecordset.MoveNext
Loop
This way you let ADO handle reading the data and removing the double-quotes and you can manipulate the data easily as a Recordset.
Just give a try for this code by replacing the path of your CSV file and tell me how it works on your side ?
Option Explicit
Dim Data
Call ForceCScriptExecution()
Data = ReadFile("C:\Test\Test.csv")
wscript.echo "Before Replacing"
wscript.echo String(50,"-")
wscript.echo Data
wscript.echo String(50,"-")
wscript.echo "After Replacing"
wscript.echo String(50,"-")
wscript.echo Search_Replace(Data)
wscript.echo String(50,"-")
wscript.sleep 20000
'-----------------------------------------------
Function Search_Replace(Data)
Dim oRegExp,strPattern1,strPattern2
Dim strReplace1,strReplace2,strResult1,strResult2
strPattern1 = ";(\x22)(\S+\w+)(\x22);"
strReplace1 = ";$2;"
strPattern2 = "[;]\x22([^\x22]+)\x22"
strReplace2 = ";'$1'"
Set oRegExp = New RegExp
oRegExp.Global = True
oRegExp.IgnoreCase = True
oRegExp.Pattern = strPattern1
strResult1 = oRegExp.Replace(Data,strReplace1)
oRegExp.Pattern = strPattern2
strResult2 = oRegExp.Replace(strResult1,strReplace2)
Search_Replace = strResult2
End Function
'-----------------------------------------------
Function ReadFile(path)
Const ForReading = 1
Dim objFSO,objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path,ForReading)
ReadFile = objFile.ReadAll
objFile.Close
End Function
'----------------------------------------------
Sub ForceCScriptExecution()
Dim Arg, Str, cmd, Title
Title = "Search and Replace using RegExp by Hackoo 2019"
cmd = "CMD /C Title " & Title &" & color 0A & Mode 80,30 & "
If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
Str = Str & " " & Arg
Next
CreateObject( "WScript.Shell" ).Run _
cmd & "cscript //nologo """ & _
WScript.ScriptFullName & _
""" " & Str
WScript.Quit
End If
End Sub
'-----------------------------------------------
Edit : Batch Script Code
You can do it easily with a batch script without using Regex :
#echo off
Title Edit CSV File
Set "Input_CSV_File=C:\Test\Test.csv"
Set "OutPut_CSV_File=C:\Test\OutPut_Test.csv"
If Exist "%OutPut_CSV_File%" Del "%OutPut_CSV_File%"
#for /f "tokens=1,2,3 delims=;" %%a in ('Type "%Input_CSV_File%"') Do (
echo "%%~a";%%~b;'%%~c'
echo "%%~a";%%~b;'%%~c'>>"%OutPut_CSV_File%"
)
TimeOut /T 5 /NoBreak>nul
If Exist "%OutPut_CSV_File%" Notepad "%OutPut_CSV_File%" & Exit

Excel VBA - Returning Positions of all Sub-Strings within a String from the Clipboard

I'm trying to find all the positions of the unique keys (followed by two Tab keystrokes) in a string in taken from clipboard, positions with which I then hope to use to insert carriage returns, and then have everything put back into the clipboard again.
First things first; getting the position part to work!
Here is a shortened example of the string:
Initial Approval in First Market or Non-Submitted Closure 090052fb842ef82f 090052fb842f3659 090052fb842ef82e
Here is the non-functional code I have put together so far from researching the problem:
Sub oldRecords()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb)[0-9A-Za-z]{8}\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
Start = 1
Do
pos = InStr(Start, strContents, objRegEx.Execute(strContents), vbBinaryCompare)
If pos > 0 Then
Start = pos + Len(objRegEx.Pattern)
WScript.Echo pos
WScript.Echo Mid(strContents, pos, Len(objRegEx.Pattern))
End If
Loop While pos > 0
End Sub
Right now I am getting a Run-time error '450': Wrong number of arguments or invalid property assignment, and I believe the culprit is:
objRegEx.Execute(strContents)
I'm not sure where to go from here, so any help would be fantastic! :)
Edit 1:
Firstly thank you for the interest in my issue!
BrackNicku has provided a simple solution for a problem I evidently thought more complex than it needed to be! Here is the code I finally went with, adding in a few extra bits that I needed on top of the core issue:
Sub oldRecords2()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Dim start As Long, pos As Long
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Dim objRegEx
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
X1 = 10 ' Line Feed Character
X2 = 13 ' Carriage Return Character
X3 = "Archive Custodain Group"
X4 = "Archive Custodain Group" & Chr(X2)
'======================================================================================================
strContents = Replace(strContents, Chr(X1), "") ' REMOVES LINE FEEDS
strContents = Replace(strContents, X3, X4) ' ADDS CR AFTER TITLE ROW
strContents = objRegEx.Replace(strContents, "$1" & vbNewLine)
'======================================================================================================
clipboard.SetText strContents 'PUT BACK INTO CLIPBOARD
clipboard.PutInClipboard
End Sub
When you run objRegEx.Execute(strContents), it returns a match collection. Then, you are not even using the results as Len(objRegEx.Pattern) returns the length of the pattern and not the match.
It seems you just want to obtain the matches and their indices in the string. Remove all starting from Start = 1 and ending with Loop While pos > 0 and use
Dim ms As Object, m As Object
'...
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
'...
Set ms = objRegEx.Execute(strContents)
For Each m In ms
WScript.Echo m.FirstIndex
WScript.Echo m.SubMatches(0)
Next
Tested with
strContents = "Initial Approval in First Market or Non-Submitted Closure" & vbTab & vbTab & "090052fb842ef82f" & vbTab & vbTab & "090052fb842f3659" & vbTab & vbTab & "090052fb842ef82e" & vbTab & vbTab
Result:
59
090052fb842ef82f
77
090052fb842f3659
95
090052fb842ef82e
Note I moved the capturing group around all but tab pattern, (090052fb[0-9A-Za-z]{8})\t\t, feel free to adjust as per your needs.
I'm trying to find all the positions of the unique keys (followed by
two Tab keystrokes) in a string in taken from clipboard, positions
with which I then hope to use to insert carriage returns, and then
have everything put back into the clipboard again.
If you want to insert new lines before each key, then instead of locating the keys and inserting new lines, you could try RegExp.Replace
strContents = objRegEx.Replace(strContents, vbNewLine & "$1")
You have to modify the pattern to include whole key in the group:
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
Result:
Initial Approval in First Market or Non-Submitted Closure
090052fb842ef82f
090052fb842f3659
090052fb842ef82e
Full code (with new line after pattern):
Sub oldRecords()
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
Dim objRegEx
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(090052fb[0-9A-Za-z]{8})\t\t"
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.MultiLine = True
strContents = objRegEx.Replace(strContents,"$1" & vbNewLine)
'Put back to clipboard
clipboard.SetText strContents
clipboard.PutInClipboard
End Sub
Using your string example I came into this:
Sub findKeyPositions()
Dim str As String
Dim splitStr() As String
Dim searchStr As String
str = "Initial Approval in First Market or Non-Submitted Closure 090052fb842ef82f 090052fb842f3659 090052fb842ef82e "
splitStr() = Split(Replace(str, "090052fb", ""), " ") 'in your example i did it with 7 spaces and not vbtab
For i = LBound(splitStr) To UBound(splitStr)
searchStr = Trim(splitStr(i))
Debug.Print (InStr(1, str, searchStr, vbTextCompare))
Next i
End Sub
If I understand your post correctly you want to replace the Tabs with CR
If so, then there's no need to find the positions, you could just replace.
Sub replaceTab()
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
clipboard.SetText Replace(clipboard.GetText, vbTab, vbCrLf)
clipboard.PutInClipboard
End Sub

Regex for matching substring, but not containing word (word boundary issue)

I have 100,000 files (mostly office-type files). I'm using Excel VBA to check all the filenames that contain the word "list", but trying to avoid false positives (such as "specialist").
The answer provided for "Regex for matching substring, but not containing word" is very nearly what's required ( \b(?!String)\w*ring\w*\b ) except that my filenames do not have neat word boundaries.
The current pattern \b(?!specialist)\w*list\w*\b correctly ignores some variants (3 Specialist, 6-specialist, Specialists etc). Is it possible to modify the pattern so that it correctly weeds out the following variants as well: 1Specialist, 2_specialist and Xspecialists? If so, could someone please point me in the right direction?
Many thanks for any assistance/advice,
M
Here's the recursive subroutine that I've been using (apologies for poor formatting):
Sub RecursiveFolderPATTERN(objFolder As Scripting.Folder, _IncludeSubfolders As Boolean)
'Declare the variables
Dim objFile As Object
Dim objSubFolder As Scripting.Folder
Dim NextRow As Long
Dim objRegExp As Object
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.Pattern = "([^A-Za-z]|^)(address|info|data)?lists?([^A-Za-z]|$)"
objRegExp.IgnoreCase = True
'Find the next available row
NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1
'Loop through each file in the folder
For Each objFile In objFolder.Files
If objRegExp.test(objFile) Then
Cells(NextRow, "A").Value = objFile.Name
Cells(NextRow, "E").Value = objFile.Size
Cells(NextRow, "F").Value = objFile.Type
Cells(NextRow, "G").Value = objFile.DateCreated
Cells(NextRow, "H").Value = objFile.DateLastAccessed
Cells(NextRow, "I").Value = objFile.DateLastModified
Cells(NextRow, "J").Value = objFile.Path
NextRow = NextRow + 1
End If
Next objFile
'Loop through files in the subfolders
If IncludeSubfolders Then
For Each objSubFolder In objFolder.Subfolders
Call RecursiveFolderPATTERN(objSubFolder, True)
Next objSubFolder
End If
End Sub
Answer edit: Changing the line If objRegExp.test(objFile) Then into If objRegExp.test(objFile.Name) Then fixed the issue.
Alternative answer edit: Changing the pattern from "([^A-Za-z]|^)(address|info|data)?lists?([^A-Za-z]|$)" to "(^(?!.*specialist).*list.*$)" also works well. Both approaches have their advantages, so I intend to use both of them.
If your goal is to find filenames that match to "list" but don't match "specialist", try the following regex:
(?i)^(?!.*specialist).*list.*$
EDIT
Delete the (?i) from the pattern and test it with the following snippet:
Sub RecursiveFolderPATTERN()
Dim objRegExp As Object, arrStrings() As String, _
i As Long, objMatch As Object
Set objRegExp = CreateObject("VBScript.RegExp")
With objRegExp
.Global = True
.IgnoreCase = True
.MultiLine = False
.Pattern = "^(?!.*specialist).*list.*$"
End With
Dim TestString As String
TestString = "3 Specialist" & vbNewLine & _
"6-specialist" & vbNewLine & _
"Specialists" & vbNewLine & _
"true SpeciaList" & vbNewLine & _
"1 Specialist" & vbNewLine & _
"2_specialist" & vbNewLine & _
"Xspecialists" & vbNewLine & _
"TheListOfSpecialists.xlsx" & vbNewLine & _
"List" & vbNewLine & _
"lISTs" & vbNewLine & _
"Globalistics" & vbNewLine & _
"GlobalList.doc" & vbNewLine & _
"fatalistic" & vbNewLine & _
"The big list of PII.csv" & vbNewLine & _
"A few lISTs with something.xls"
arrStrings = Split(TestString, vbNewLine)
For i = LBound(arrStrings) To UBound(arrStrings)
If objRegExp.Test(arrStrings(i)) Then
Debug.Print arrStrings(i)
End If
Next
End Sub
Would something like this work for you?
([^A-Za-z]|^)list([^A-Za-z]|$)
It would match the word "list" that is not surrounded by other letters.
Or should some words containing "list" be acceptable?
Try it out
EDIT: To allow matching the word "lists" it can be changed to this:
([^A-Za-z]|^)lists?([^A-Za-z]|$)
EDIT 2: To whitelist some prefixes, you can change it to this (whitelists "address", "info" and "data" as prefixes for example purposes):
([^A-Za-z]|^)(address|info|data)?lists?([^A-Za-z]|$)

Find text between two static strings

I parse message data into a CSV file via Outlook rules.
How can I take the example below and store the text under "Customer Log Update:" into a string variable?
[Header Data]
Description: Problem: A2 - MI ERROR - R8036
Customer Log Update:
I'm having trouble with order #458362. I keep getting Error R8036, can you please assist?
Thanks!
View problem at http://...
[Footer Data]
Desired result to be stored into the string variable (note that the result may contain newlines):
I'm having trouble with order #458362. I keep getting Error R8036, can you please assist?
Thanks!
I haven't attempted to code anything pertaining to my question.
Function RegFind(RegInput, RegPattern)
Dim regEx As New VBScript_RegExp_55.RegExp
Dim matches, s
regEx.Pattern = RegPattern
regEx.IgnoreCase = True
regEx.Global = False
s = ""
If regEx.Test(RegInput) Then
Set matches = regEx.Execute(RegInput)
For Each Match In matches
s = Match.Value
Next
RegFind = s
Else
RegFind = ""
End If
End Function
Sub CustomMailMessageRule(Item As Outlook.MailItem)
MsgBox "Mail message arrived: " & Item.Subject
Const FileWrite = file.csv `file destination
Dim FF1 As Integer
Dim subj As String
Dim bod As String
On Error GoTo erh
subj = Item.Subject
'this gets a 15 digit number from the subject line
subj = RegFind(subj, "\d{15}")
bod = Item.Body
'following line helps formatting, lots of double newlines in my source data
bod = Replace(bod, vbCrLf & vbCrLf, vbCrLf)
'WRITE FILE
FF1 = FreeFile
Open FileWrite For Append As #FF1
Print #FF1, subj & "," & bod
Close #FF1
Exit Sub
erh:
MsgBox Err.Description, vbCritical, Err.Number
End Sub
While I would also go the more direct route like Jean-François Corbett did as the parsing is very simple, you could apply the Regexp approach as below
The pattern
Update:([\S\s]+)view
says match all characters between "Update" and "view" and return them as a submatch
This piece [\S\s] says match all non-whitespace or whitespace characters - ie everything.
In vbscript a . matches everything but a newline, hence the need for the [\S\s] workaround for this application
The submatch is then extracted by
objRegM(0).submatches(0)
Function ExtractText(strIn As String)
Dim objRegex As Object
Dim objRegM As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.ignorecase = True
.Pattern = "Update:([\S\s]+)view"
If .test(strIn) Then
Set objRegM = .Execute(strIn)
ExtractText = objRegM(0).submatches(0)
Else
ExtractText = "No match"
End If
End With
End Function
Sub JCFtest()
Dim messageBody As String
Dim result As String
messageBody = "Description: Problem: A2 - MI ERROR - R8036" & vbCrLf & _
"Customer Log Update:" & _
"I 'm having trouble with order #458362. I keep getting Error R8036, can you please assist?" & vbCrLf & _
"Thanks!" & vbCrLf & _
"View problem at http://..."
MsgBox ExtractText(messageBody)
End Sub
Why not something simple like this:
Function GetCustomerLogUpdate(messageBody As String) As String
Const sStart As String = "Customer Log Update:"
Const sEnd As String = "View problem at"
Dim iStart As Long
Dim iEnd As Long
iStart = InStr(messageBody, sStart) + Len(sStart)
iEnd = InStr(messageBody, sEnd)
GetCustomerLogUpdate = Mid(messageBody, iStart, iEnd - iStart)
End Function
I tested it using this code and it worked:
Dim messageBody As String
Dim result As String
messageBody = "Description: Problem: A2 - MI ERROR - R8036" & vbCrLf & _
"Customer Log Update:" & vbCrLf & _
"I 'm having trouble with order #458362. I keep getting Error R8036, can you please assist?" & vbCrLf & _
"Thanks!" & vbCrLf & _
"View problem at http://..."
result = GetCustomerLogUpdate(messageBody)
Debug.Print result