简体   繁体   中英

How to set variable as row number in VBA?

I have a code that inserts a row at the end of a section and and then copies formulas from above.

My only problem is that I am not sure how to define a variable such as "iRow" as a dynamic range.

The code below is the part that copies the formulas only from the row above. If I set iRow as a fixed number, the whole code works. However, I need the "iRow"-variable to take on whatever row number in which the value "2" can be found in column B.

I have tried things like Columns("B:B").Find(What:=2).

Application.ScreenUpdating = True

  Dim iRow As Integer
  iRow = ???
  'Select row
  Rows(iRow - 1).EntireRow.Copy
  'Paste it into the new row
  Rows(iRow).PasteSpecial

  Rows(iRow).SpecialCells(xlConstants).ClearContents

Application.CutCopyMode = False

To answer your question:

"However, I need the "iRow"-variable to take on whatever row number in which the value "2" can be found in column B."

You probably need something like:

Sub test()

Dim iRow as Long
With Sheet1 'Use an explicit sheet reference, use a sheets CodeName
    iRow = .Columns(2).Find(2, lookat:=xlWhole).Row
    'Rest of code
End With

End Sub

This will get the row number of the first occurrence of 2. If no value of two is found this will yield an error though.

If you want a dynamic row counter, you need a count. with the below code, if you set the column to B for example and use a counter, it will always look for the last row.

For Example

Application.ScreenUpdating = True
Dim iRow As Integer
'This will give the last number in the row that is filled
iRow = .Range("B" & .Rows.Count).End(xlUp).Row
'Select row
Rows(iRow - 1).EntireRow.Copy
'Paste it into the new row
Rows(iRow).PasteSpecial

 Rows(iRow).SpecialCells(xlConstants).ClearContents

Application.CutCopyMode = False

I would also declare the workbook and worksheet, but in this example, I left it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM