作者:qiqianan | 来源:互联网 | 2023-05-18 17:08
IhaveaproblemthatIdontunderstandatall:我有一个我完全不明白的问题:i150IfActiveWorkbook.Worksheet
I have a problem that I don't understand at all:
我有一个我完全不明白的问题:
i = 150
If ActiveWorkbook.Worksheets("foobar").Cells(i, 3).Value Like "*:*" Then
MsgBox "I found a colon!"
End If
As you might guess, the sheet foobar has at position (150, 3) a cell containing a colon, thus the message box is shown.
正如您可能猜到的那样,表格foobar在位置(150,3)处有一个包含冒号的单元格,因此会显示消息框。
Now I want to do this:
现在我想这样做:
i = 150
Cell = ActiveWorkbook.Worksheets("foobar").Cells(i, 3).Value 'fails right here
If Cell Like "*:*" Then
MsgBox "I found a colon!"
End If
Here it gives me an error saying "Object variable or With block variable not set. In fact saying:
这里给出了一个错误,说“对象变量或者没有设置块变量。实际上说:
Sheet = ActiveWorkbook.Worksheets("foobar")
gives a similar message. Why? What am I doing wrong? I just want a reference of that object, or at least a refence.
给出了类似的信息。为什么?我究竟做错了什么?我只想要一个对象的引用,或者至少是一个refence。
5 个解决方案
6
Bottomline:
- When handling objects, use
Set
.
处理对象时,请使用Set。
- When handling primitive data (integers, longs, strings*, variants*) you do not use it.
处理原始数据(整数,长整数,字符串*,变体*)时,不要使用它。
Sheet
, Workbook
, Range
, are objects. Therefore, you need to use Set
when assigning them to variables.
工作表,工作簿,范围,是对象。因此,在将它们分配给变量时需要使用Set。
A Range.Value
returns a Variant (that can be a long, a string, etc.) So, you cannot use Set
.
Range.Value返回Variant(可以是long,字符串等)。因此,您不能使用Set。
==========================
Now, about your error message... I'd say then that maybe before in your code, Cell
is being declared as object. Try use another variable name, or check the Cell variable type.
现在,关于你的错误信息...我当时可能会说,在你的代码之前,Cell被声明为对象。尝试使用另一个变量名,或检查Cell变量类型。
To check this, right click on it and then click in 'Definition'. Have it declared as Variant
might fix the problem (be aware of side effects it might cause, though).
要检查这一点,请右键单击它,然后单击“定义”。将它声明为Variant可能会解决问题(但要注意它可能导致的副作用)。
==========================
*I know these types aren't 'primitive'; I used as an example here for the sake of explanation's cleanliness.
*我知道这些类型不是“原始的”;为了解释清洁,我在这里举了一个例子。