I am trying to extract the text between two occurrences of sub strings in a string using the character @ as a marker. I know there are 8 occurrences of @. I want to loop through the main string, and write the sub strings to the sheet.
Although I provided a Dim expression for the string textBetween I get the error msg "Error msg "Object variable or With block variable not set". I cannot figure why.
The code comes from excel vba- extract text between 2 characters, so it should be easy, right? Well, not for me!
I have fiddled with it for several hours, without results.
Sub FindStrings()
Dim sheet2 As Worksheet
Dim i As Integer
Dim openPos As Long
Dim clsPos As Long
Dim textBetween As String
openPos = 0
'Using for loop to find the i th occurrence of at '@' for openPos
For i = 1 To 8
'get position of start of string
openPos = InStr(openPos + i, sheet2.Range("H8"), "@", vbTextCompare)
'Error msg "Object variable or With block variable not set
'get position of end of string
clsPos = InStr(openPos + 1 + i, sheet2.Range("H8"), "@",
vbTextCompare) 'End of string
'get the mid string value between openPos and clsPos
'
textBetween = Mid(sheet2.Range("H8").Value, openPos + 1, clsPos -
openPos - 1)
MsgBox ("textBetween " & "i" & textBetween)
'write to sheet
sheet2.Cells(7 + i, 8).Value = textBetween
Next i
End Sub
I expect to write the strings to the worksheet. The error message is:"Error msg "Object variable or With block variable not set"
Dim sheet2 As Worksheetbut never assign a worksheet to that variable.sheet2object before you can use it.@thenDim arr: arr = Split(sheet2.Range("H8").Value, "@")will do that.