Too many qs
Too many qs

Reputation: 45

VBA - How to declare "Cell" variable

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.

Thank you for your help in advance :)

Upvotes: 2

Views: 21845

Answers (4)

Harassed Dad
Harassed Dad

Reputation: 4704

Sorry but that is horrible code and it offends the eyes. Find would be better, but just in the interest of better understanding

 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

Upvotes: 0

Alex K.
Alex K.

Reputation: 175758

Walking over a Range yields a Range so Dim Cell As Range

If in doubt ask VBA: msgbox TypeName(Cell)

Upvotes: 2

braX
braX

Reputation: 11755

You can use Range. They are somewhat interchangeable.

Upvotes: 1

FunThomas
FunThomas

Reputation: 29171

In your case, cell is a range, so

dim cell as range

And: Always use Option Explicit

Upvotes: 3

Related Questions