Home » excel » Excel VBA – transpose formulas in vertical array to horizontal array

Excel VBA – transpose formulas in vertical array to horizontal array

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have googled all sorts of phrases for an answer to my question but I’m having a hard time locating a solution that works. It likely involves combination of a few different solutions, or a method I have yet to think of; so any help would be appreciated.

Say I have formulas in cells A1, A2, A3, and A4. Let’s say I want those EXACT formulas moved to the right one column.

In VBA I can say:

Range("B1:B4").Formula = Range("A1:A4").Formula

What I’m looking to do is something like this:

Range("B1:E1").Formula = Range("A1:A4").Formula

See how my B:E range is horizontal verses the vertical range of A1:A4.

I have tried all sorts of transpose options but I can’t find any that work because I want the EXACT formula’s to transfer.

Any thoughts?

How to&Answers:

You could try something like:

Sub PivotRangeFormulas()
    Dim rngSrc As Range: Set rngSrc = ActiveSheet.Range("A1:A4")
    Dim rngTgt As Range: Set rngTgt = ActiveSheet.Range("B1:E1")
    Dim i As Long: For i = 1 To rngSrc.Rows.Count
        Application.Index(rngTgt, i).Formula = Application.Index(rngSrc, i).Formula
    Next i
End Sub

You could also use an Offset function from the first cell in each range

Answer:

Range("B1:E1").Formula = WorksheetFunction.Transpose(Range("A1:A4").Formula)

Answer:

Is locking the cell reference inside your formulas possible? I’m sure you are aware, but the F4 key (pc) will toggle referenced cell locks. The dollar sign locks the column letter or row number [A6, $A$6, A$6, $A6]. If you lock your cell references, you can then copy and transpose the formulas.

Range("B1:E1").Copy
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=True

Here is another option: Try recording a macro while entering your formula in the cell. If your formula is:

=SUM(D3:D4) 

Depending on where you entered the formula, the VBA output might look like:

"=SUM(R[3]C:R[4]C)"

Here is the absolute reference in VBA:

"=SUM(R3C4:R4C4)"

You could then do something like:

Range("A8:A23").FormulaR1C1 = "=SUM(R3C4:R4C4)"

This will enter the formula =SUM($D$3:$D$4) in all the cells from “A8:A23”. If you play with the brackets in the VBA formula, you should be able to make it work. The formula below searches the column to the left of the selected cell(s) containing the formula for the text “nff”:

    Selection.FormulaR1C1 = _
    "=SEARCH(""nff"",RC[-1])"