简体   繁体   中英

How to select a cell in excel VBA?

I've applied some formula in the cell P2. I want to apply the same formula(like ctrl + D) in all cells in that column P, until i've values in column C.

Range("C1").Select
Selection.End(xlDown).Select
lastcell_number = ActiveCell.Row
Range("P",lastcell_number).Select.

It's throwing error. How do i select last column in column P?

If the formula is already in P2 then,

with worksheets("Sheet1")
    .range(.cells(2, 3), .cells(rows.count, 3).end(xlup)).offset(0, 13).formula = _
      .range("P2").formula
end with

If the formula is not already in P2 then,

with worksheets("Sheet1")
    .range(.cells(2, 3), .cells(rows.count, 3).end(xlup)).offset(0, 13).formula = _
      "=SUM(A2:O2)"   '<~~put your own formula here
end with

To select the last cell always come up from the bottom of the sheet as opposed to down from the top, this is because any blank row will be the first place it stops giving you a false row number.

lastcell_number = Range("C" & Rows.Count).End(xlup).row

Also note, you don't need to select it to find out what it is. Typically there are very few cases where you actually need to select inside code.

This:

Range("A1").select
MyStr = Selection.text
Range("B1").select
Selection.Formula = MyStr

can be written as this:

MyStr = Range("A1").text
Range("B1").Formula = MyStr

Assuming you don't need MyStr anywhere else in the code it can then be condensed again to this:

Range("B1").Formula = Range("A1").text

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