VBA - 如何声明“Cell”变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45194548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA - How to declare "Cell" variable
提问by Too many qs
Apologies for the potentially very easy to answer question. I was trawling through some code on the site regarding how you search for a row and paste it in another worksheet, the code being the one below:
对于可能很容易回答的问题表示歉意。我在网站上浏览了一些关于如何搜索行并将其粘贴到另一个工作表中的代码,代码如下:
Sub Test()
For Each Cell In Sheets(1).Range("J:J")
If Cell.Value = "131125" Then
matchRow = Cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Sheet2").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Sheet1").Select
End If
Next
End Sub
I was wondering what the "Cell" should be declared as, as in:
我想知道“单元格”应该声明为什么,如下所示:
Dim Cell As ...
I'm aware that without "Option Explicit", this is irrelevant, but I'm curious nonetheless, so please do help and explain if you can.
我知道如果没有“Option Explicit”,这是无关紧要的,但我仍然很好奇,所以如果可以,请提供帮助和解释。
Thank you for your help in advance :)
提前谢谢你的帮助 :)
回答by FunThomas
In your case, cell
is a range
, so
在你的情况下,cell
是 a range
,所以
dim cell as range
And: Alwaysuse Option Explicit
并且:始终使用Option Explicit
回答by Alex K.
Walking over a Range yields a Range so Dim Cell As Range
走过一个范围会产生一个范围,所以 Dim Cell As Range
If in doubt ask VBA: msgbox TypeName(Cell)
如果有疑问,请询问 VBA: msgbox TypeName(Cell)
回答by Harassed Dad
Sorry but that is horrible code and it offends the eyes. Find would be better, but just in the interest of better understanding
对不起,这是可怕的代码,它冒犯了眼睛。Find 会更好,但只是为了更好地理解
Sub Test()
Dim Cell as Range
For Each Cell In Sheets(1).Range("J:J")
If Cell.Value = "131125" Then
Cell.EntireRow.copy Destination:=Sheets("Sheet2").range("a" & cell.row)
'You might want to exit here if there's only one value to find with
'Exit For
End If
Next
End Sub
结束子
回答by braX
You can use Range
. They are somewhat interchangeable.
您可以使用Range
. 它们在某种程度上可以互换。