我正在尝试构建逻辑,如果在特定工作表中的特定单元格中填充了特定的字符串,它将跳过运行该子项并转到下一个子项。到目前为止,我认为这是我迄今为止最接近的尝试:
Dim Rng_1 As Range
Dim x_sheet As Worksheet
Dim Value_X
Value_X = "<>Could not generate report for*"
Set x_sheet = ActiveWorkbook.Worksheets("worksheet_name")
Set Rng_1 = x_sheet.Range("B8")
If Rng_1.value = Value_X Then
'run code
End If
'It should continue from here if the referenced cell did contain the string.
运行上述命令始终会跳过两者之间的代码,无论我如何编辑不包含值的代码,甚至即使我添加“ else if”也是如此。在这一点上,我什至不确定自己是否走对了。
答案 0 :(得分:2)
处理通配符时,需要使用Like
比较运算符。为此,“不匹配”为Not this Like that
。您无需添加<>
运算符即可产生“不匹配”。
如果要使用计划A和计划B,则需要Else
。
Value_X = "Could not generate report for*" 'removed <>
Set x_sheet = ActiveWorkbook.Worksheets("worksheet_name")
Set Rng_1 = x_sheet.Range("B8")
If Not Rng_1.value Like Value_X Then
Debug.Print "msg not found"
'run code
Else
Debug.Print "msg found"
'It should continue from here if the referenced cell did contain the string.
End If
从样本数据来看,看来您也可以测试IsNumeric(Rng_1.value)
。
答案 1 :(得分:0)
根据提供的数据的外观,您可以反向工程问题,以检查数据是否格式正确(仅数字)
Private Sub loop_though()
Dim ws as Worksheet: set ws = Sheets("worksheet_name")
Dim cell as Range
Dim looprange as Range: Set looprange = ws.Range("B2:B10")
For each cell in looprange
If Not IsNumeric(cell) Then 'cell does not contain only numbers
' further code here
End If
Next cell
End Sub
或者,如果您坚持要检查单元格中的“ value_x
”,那么这将是解决方案。
Private Sub loop_though()
Dim ws as Worksheet: set ws = Sheets("worksheet_name")
Dim cell as Range
Dim looprange as Range: Set looprange = ws.Range("B2:B10")
Dim value_x as String: value_x = "Could not generate report for"
For each cell in looprange
If InStr(1, cell, value_x) <> 0 Then
' further code here
End If
Next cell
End Sub