【问题标题】:VBA - How to declare "Cell" variableVBA - 如何声明“单元格”变量
【发布时间】:2017-07-19 15:09:06
【问题描述】:

对于这个可能很容易回答的问题,我们深表歉意。我正在浏览网站上关于如何搜索一行并将其粘贴到另一个工作表中的一些代码,代码如下:

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 ...

我知道如果没有“选项显式”,这是无关紧要的,但我还是很好奇,所以如果可以的话,请帮忙解释一下。

提前感谢您的帮助:)

【问题讨论】:

    标签: vba excel variables declare


    【解决方案1】:

    在你的情况下,cellrange,所以

    dim cell as range
    

    并且:总是使用Option Explicit

    【讨论】:

      【解决方案2】:

      遍历一个范围会产生一个范围,所以Dim Cell As Range

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

      【讨论】:

        【解决方案3】:

        您可以使用Range。它们在某种程度上可以互换。

        【讨论】:

          【解决方案4】:

          对不起,那是可怕的代码,它冒犯了眼睛。查找会更好,但只是为了更好地理解

           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
          

          结束子

          【讨论】:

            猜你喜欢
            • 2023-02-17
            • 1970-01-01
            • 1970-01-01
            • 2017-05-26
            • 2019-12-06
            • 1970-01-01
            • 1970-01-01
            • 2011-02-12
            • 1970-01-01
            相关资源
            最近更新 更多