简体   繁体   中英

Excel VBA: Applying formula to multiple columns with a set row number

I've been wracking my brain to figure this out and I have a feeling that it's such an easy fix.

I have a formula that I need to apply to columns I to Z, and commencing row 3 until the last row of data in column C. I've managed to define what the "lastRow" is, but I cannot for the life of me work out how to apply the formula to columns I to Z.

Any help would be greatly appreciated! Thanks in advance :)

My VBA macro is below:

Sub Calculation()

Dim ws1 As Worksheet
Dim rng As Range
Dim lastRow As Long
Set ws1 = Sheets("Sheet 2")

With ws1
    lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    .Range("I3:I" & lastRow).Formula = "=1+2"
    
End With
End Sub

A small change in the Range

    Sub Calculation()

        Dim ws1 As Worksheet
        Dim rng As Range
        Dim lastRow As Long
        Set ws1 = Sheets("Sheet 2")

        With ws1
            lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
            .Range("Z3:I" & lastRow).Formula = "=1+2"
            
        End With
    End Sub

Let's try and understand how Range works in VBA
The VBA Range Object represents a cell or multiple cells in your Excel worksheet.

  1. A single cell : Range("A1")
  2. A row : Range("1:1")
  3. A column : Range("A: A")
  4. For Contiguous Cells : Range("A1:C5")
  5. For Non-Contiguous Cells : Range("A1:C5, F1:F5")
  6. For Intersection of two ranges : Range("A1:C5 F1:F5")
    (For intersection cell, remember there is no comma operator)

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