简体   繁体   中英

Copy formula to entire column on variable target cell

I'm very new to VBA and there are so many ways to reference a cell and I'm kind of lost here.

My excel sheet comes with the columns swapped around and there is no guarantee that a column will be in the position it was last time but I do know that total number of columns and the column header names are consistent.

So I find my column number using this:

Dim target As Range
Dim ws As Worksheet

Set ws = ThisWorkbook.ActiveSheet

With ws
   Set target = .Range("A1:M1").Find(What:="Target_Column", LookIn:= xlValues, LookAt: = xlWhole, _ 
MatchCase:=False, SeaarchFormat:=False)

targetCol = target.Column

This gives me the index number of my target column.

Now I want to apply the following function to column "N" in my worksheet (the below formula assumes target column is column "G":

"=RIGHT(G1,LEN(G1)-10)"

I want to use something similar (or easier) than the script below but don't know how to achieve this:

FinalRow = .Cells(.Rows.Count,1).End(xlUp).Row

.Range(.Cells(2,14), .Cells(FinalRow, 14)).FormulaR1C1 =
"=RIGHT(" &  targetCol & "1, LEN(" & targetCol & "1)-10)"

I hope the question is clear enough and someone can point me in the right direction.

Thanks.

Based on your description, you may try something like this... Remember that as per your description, the first formula will be in N2 and will be referencing G1, N2 will be referencing G2 and so on. Make sure that the formula is correct.

Range("N2:N" & FinalRow).Formula = "=RIGHT(" & Cells(1, TargetCol).Address(0, 0) & ",LEN(" & Cells(1, TargetCol).Address(0, 0) & ")-10)"

您可以使用

.Range(.Cells(2,14), .Cells(FinalRow, 14)).FormulaR1C1 ="=RIGHT(RC" &  targetCol & ", LEN(RC" & targetCol & ")-10)"

Maybe something slightly more flexible like:

Option Explicit

Public Sub testing()
    Dim wb As Workbook, ws As Worksheet, searchRange As Range, targetColumn As Long, lastRow As Long
    Set wb = ThisWorkbook
    Set ws = wb.ActiveSheet                      'change as appropriate

    Const header As String = "MyHeader"          '<====Change to header name trying to find
    Const startFormulaRow As Long = 2            '<=== change for column to start applying formula at.  Assume not 1 as contains header
    Const formulaColumn As Long = 14             '<==== change for column you want to apply formula in
    Const charsToRemove As Long = 10             '<=== change to different number of characters to remove from len
    With ws
        Set searchRange = .Range("A1:M1")        '<===Change to alternative search range
        targetColumn = FindTargetColumn(header, searchRange)

        If targetColumn > 0 Then
            lastRow = GetLastRow(ws, targetColumn, startFormulaRow)
            .Range(.Cells(startFormulaRow, formulaColumn), .Cells(lastRow, formulaColumn)).FormulaR1C1 = "=IFERROR(RIGHT(RC" & targetColumn & ",LEN(RC" & targetColumn & ")-" & charsToRemove & "),"""")"
        End If
    End With
End Sub

Public Function FindTargetColumn(ByVal header As String, ByVal searchRange As Range) As Long
    Dim target As Range
    Set target = searchRange.Find(What:=header, LookIn:=xlValues, LookAt:=xlWhole, _
                                  MatchCase:=False, SearchOrder:=xlRows, SearchFormat:=False)
    If Not target Is Nothing Then
        FindTargetColumn = target.Column
    Else
        FindTargetColumn = -1
    End If
End Function

Public Function GetLastRow(ByVal ws As Worksheet, ByVal targetColumn, ByVal startFormulaRow As Long) As Long
    If Not Application.WorksheetFunction.Subtotal(103, ws.UsedRange) = 0 Then
        GetLastRow = ws.Columns(targetColumn).SpecialCells(xlCellTypeLastCell).Row
    Else
        MsgBox "No data in " & ws.Name & " or last row is < than required formula start row of " & startFormulaRow
        End
    End If
End Function

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