我正在尝试使用字符@作为标记来提取字符串中两次出现的子字符串之间的文本。我知道有8次@。我想遍历主字符串,然后将子字符串写入工作表。
尽管我为字符串textBetween提供了Dim表达式,但出现错误msg“错误msg”对象变量或未设置块变量“。我不知道为什么。
代码来自excel vba- extract text between 2 characters,所以应该很容易,对吧?好吧,不适合我!
我已经弄了几个小时,没有结果。
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
我希望将字符串写入工作表。错误消息为:“错误消息”未设置对象变量或带块变量”
答案 0 :(得分:0)
您需要先设置/创建sheet2对象,然后才能使用它。
Dim sheet2 as Worksheet
Set sheet2 = Sheets("Sheet2")
或者,如果将VBE中的图纸名称引用从“ Sheet 2”更改为sheet2,则不再需要将sheet2声明为工作表。
答案 1 :(得分:0)
Dim sheet2 As Worksheet
...
sheet2.Range("H8")
您已经声明了 sheet2 变量,但从未将其Set
声明为工作表对象。碰巧的是,工作簿中的第二个工作表有一个Worksheet.Codename property可以用作对象引用。如果您打算引用该工作表,则引用sheet2.Range("H8")
将起作用;不需要声明Dim sheet2 As Worksheet
。如果您打算引用另一个工作表,请不要使用 sheet2 ,因为第二个工作表的代号与代表设置对象的声明变量之间可能会混淆。您还必须将Set
变量更改为工作表对象。
'write to sheet
sheet2.Cells(7 + i, 8).Value = textBetween
上面的代码在For ... Next循环的第一次迭代中将 textBetween 写入sheet2.Range("H8")
。后续循环会重新读取覆盖的值,因此您的结果将不会达到您的期望。
您最好的选择是将字符串拆分为从零开始的数组,然后选择要返回的片段。 UserDefined函数可以在公共子目录中使用,也可以直接在工作表中使用。
Option Explicit
Sub FindStrings()
Dim i As Long
Dim textBetween As String
For i = 1 To 8
textBetween = FindNthString(Sheet2.Range("H8").Value, i)
'write to sheet
Sheet2.Cells(8 + i, "H").Value = textBetween
Next i
End Sub
Function FindNthString(str As String, ndx As Long, _
Optional delim As String = "@")
FindNthString = CVErr(xlErrNA)
'Split uses a zero-based array by default
'the first 'piece' is at position 0
ndx = ndx - 1
If UBound(Split(str, delim)) >= ndx And ndx >= 0 Then
FindNthString = Split(str, delim)(ndx)
End If
End Function