如果语句来检查macros中的Excel单元格

我试图做一个If语句,检查给定的单元格是否存在(一些是合并),并有一个不同的价值' – ',语句执行,在这种情况下,一个查询。 如果条件不满足,则不执行查询

CellStr = Range("C3").Text If CellStr <> "-" Then Set rs = conn.Execute("QUERY") End If 

我提供的代码在单元格的值为' – '(查询不执行)时工作,但当单元格不存在时不起作用(查询执行并返回0)

如何保护If语句对这个问题?

在检查单元格中的值/文本之前,请检查单元格是否存在(即未被合并的单元格覆盖):

 Sub test() Dim c As Range Set c = Range("C3") 'Set the cell 'Check if the cell exists, ie is not covered by merged cells If c.MergeArea.Cells(1, 1).Address = c.Address Then 'Check if the cell text is different from "-" If c.Text <> "-" Then 'Execute something MsgBox "Put your statement here" End If End If End Sub 

最好的祝福,

西蒙