VBA – 如何声明“单元格”variables

为可能非常容易回答的问题道歉。 我正在通过网站上的一些代码来搜寻如何search一行并将其粘贴到另一个工作表中,代码如下所示:

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 

我想知道应该宣布什么“单元格”,如下所示:

 Dim Cell As ... 

我知道,没有“Option Explicit”,这是不相关的,但我很好奇,所以请帮忙解释一下,如果可以的话。

提前谢谢你的帮助 :)

在你的情况下, cell是一个range ,所以

 dim cell as range 

并且: 始终使用Option Explicit

越过一个范围产生一个范围,所以Dim Cell As Range

如果有疑问请问VBA: msgbox TypeName(Cell)

你可以使用Range 。 它们有些可以互换。

对不起,但这是可怕的代码,它冒犯了眼睛。 发现会更好,但只是为了更好的理解

  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 

结束小组