Excel VBA - transpose formulas in vertical array to horizontal array - vba

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?

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

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

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])"

Related

Copy Formula to a range

Would like to copy a formula from a cell to a range by using variables. It works fine with xlPasteFormulas but want to avoid it. This formula used wrong references so endresult is wrong:
With ActiveSheet
.Range(.Cells(rowStarWs1, colAct), .Cells(rowLast, colAct)).Formula = .Cells(rowSuch2Ws1, colAct).Formula
End With
Example:
Formula is saved in cell C3 (e.g. A3*B3)
Would like to paste the formula to range C10:C13. Range is given by my variables.
Result should look like below (Yellow cells)
I find using R1C1 notation very helpful when moving formulas around, especially in simple cases like the one you illustrated. More consideration is needed for more complex cases.
Sub f()
Dim f As String
f = Range("C3").FormulaR1C1
Range("C10:C13").FormulaR1C1 = f
End Sub
or
Range("C10:C13").FormulaR1C1 = Range("C3").FormulaR1C1
You might use FillDown for this purpose.
Cells(10, 3).Formula = Cells(3, 3).FormulaR1C1
Range("C10:C14").FillDown
FillDown copies the formula from the first cell of the defined range to all its cells. Therefore the first line of code fills that first cell. Assigning the R1C1 format to the Formula property changes the cells referenced in the formula without using the R1C1 format in the output.

How to highlight a cell based on another cells value VBA?

This question has been asked before but I went about doing it another way. I am trying to highlight a cell if it is greater than the value of another cell.
Here is my code:
Sub Error_Search()
Dim Summary As Worksheet
Dim lr As Long
Set Summary = Worksheets("Summary")
lr = Cells(Rows.Count, 20).End(xlUp).Row
With Summary
For i = lr To 3 Step -1
If Range("L" & i).Value > Range("$Q$2:$R$3").Value Then Range("L" & i).Font.Color = -16776961
Next i
End With
End Sub
Range("$Q$2:$R$3") is a merged cell and it is the cell I want to compare the cell I want to highlight to.
I keep getting a mismatch error.
Any help would be greatly appreciated.
Thanks,
G
As mentioned in the comments, the problem is that a multiple-cells Range doesn't have a single Value, even if the cells are merged: Range.Value yields a 2D variant array whenever more than a single cell is involved. So you can fix the bug by only referring to the top-left cell of the merged range instead.
That said...
You don't need any VBA code to do this; conditional formatting handles it quite neatly.
=$C4>$M$3
Note the $ dollar signs: $M$3 would be your merged cell (only the leftmost cell matters), and $C4 is just the first cell you're defining the conditional format into; leaving the row non-absolute (i.e. no $ on the row number) allows you to apply the format to an entire range of cells by specifying the Applies to range:
Note that the format formula is the same regardless of whether we're looking at $M$3 or $M$3:$N$3 merged cells.
Conditional formats will perform much better than any VBA code you can write.

VBA Runtime Error 1004 “Application-defined or Object-defined error” when setting Range in macro

I'm going to preface this by saying that I am very new to VBA and this is my first project with it however, I'm trying quite hard because otherwise it is manual copy paste ~200 times.
Unfortunately, for a first project it has been difficult.
EDITED FOR CLARITY (HOPEFULLY): The main idea is that I need to start at the beginning of a drop down list, copy the first string listed, then paste that string down the column. This changes the numerical data adjacent to the right. I then want to select this newly changed numerical data and copy and paste it to a different sheet in the same workbook in the first blank space in column F. I then want the code to iterate through the drop down list and do this for all 51 strings in the drop down. However it needs to paste offset by 3 columns for each iteration to copy the data to the correct column in the other sheet.
Here is my code thus far
Option Explicit
Sub PtComp()
'
' PtComp Macro
'
'
Dim List1 As String
Dim Range1 As Range
Dim Line1 As Range
Dim i As Integer
Dim Begin As Range
ActiveWorkbook.Sheets("Sample Data Summary").Activate
List1 = Selection
Set Range1 = Evaluate(ActiveSheet.Range(List1).Validation.Formula1)
For Each Line1 In Range1
Selection.Copy
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
ActiveCell.Offset(0, 1).Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
ActiveSheet.Selection.Copy
ActiveWorkbook.Sheets("Pt Comparison").Activate
Begin = ActiveSheet.Range("F1").End(xlDown).Offset(-1, 0)
For i = 0 To 148 Step 3
Begin.Offset(0, i).Select
ActiveSheet.PasteSpecial Paste:=xlPasteValues
Next i
Next Line1
End Sub
It is highlighting this line
Set Range1 = Evaluate(ActiveSheet.Range(List1).Validation.Formula1)
Any help would be greatly appreciated. Sorry if my code is trash, like I said, first timer hoping to get better.
EDIT: Also, I looked back at older questions with the same error and thought that it was maybe because it wasn't clear what worksheet I was trying to define the range in, hence why my code is full of 'ActiveSheet' but still no luck.
Your code assumes List1 contains a valid range address, and thus that the active cell on that "Sample Data Summary" worksheet, contains a valid range address.
Apparently that isn't always the case. Search for more details on the On Error statement for ideas about how you could go about handling that situation.
You need to read up on How to avoid using Select in Excel VBA macros, and know that clipboard operations in a tight loop is pretty much the single slowest thing you can do in Excel-VBA.
Seems you want something like this:
Set Range1 = Evaluate(Selection.Validation.Formula1)
Your code blows up on Range(List1) because List1 does not contain a valid range address.

VBA Code to copy and paste active column with merged cells inside

I'm trying to copy the active column and paste it next to it but the code selects the entire worksheet because it has merged cells in.
Sub CopyPaste()
Columns(ActiveCell.Column).Selection
Selection.Copy
ActiveCell.Offset(0,1).PasteSpecial Paste:=xlPasteAll
End Sub
Could you please help me adding the missing code to ignore merged cells?
This is yet another reason to avoid using Select in VBA for Excel. Your selection will expand with the merged cells. You can try this:
ActiveCell.EntireColumn.Copy ActiveCell.Offset(0, 1).EntireColumn
And again, you should find some way to avoid counting on the ActiveCell in your code, and use some fully qualified range.

excel click object stores value from one cell to another

I'm trying to work on something in excel VBA but I can't seem to make it work fine.
Here's how it should work:
I need to copy and paste value of "J21" cell from one sheet to another. BUT, value of J21 keeps on changing every week. So I thought what if I create a code where I'll just press an object (say "STORE!") and it copies the value of "J21" from Sheet1 to "C3" Sheet 2. Then when the value of J21 changes, I just press "STORE!" again and it will copy the value of J21 and paste it on "C4" Sheet 2 without changing the previous value on "C3" Sheet 2.
Here's my latest attempt:
Dim myCell As Range, myRange As Range, i As Long
i = 3
Set myRange = Sheets("Summary").Range("C3")
Set myRange = Range(myRange, myRange.End(xlDown))
Sheets("Sheet1").Select
Range("J21").Copy
Sheets("Summary").Select
Cells(i, 3).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
i = i + 1
myCell and myRange were used for my previous attempts, but it always go on an infinite copy-paste.
Selection and copy-paste in VBA is usually not needed. If you want to modify the value of a cell it is better to just directly use the value property of a range object. You seem to want to establish a reference to the first blank cell below C2 on Sheet2. The problem with your code is that Range(myRange, myRange.End(xlDown)) selects an entire block of cells (above the cell you want) rather than a single cell. While it would be possible to use .End(xlDown) appropriately to get to the cell you want, it is somewhat tricky to get right since it behaves differently depending on whether or not the cell underneath the current cell is blank. A while loop is one way to go. Something like:
Sub store()
Dim target As Range, source As Range
Set source = Sheets("Sheet1").Range("J21")
Set target = Sheets("Sheet2").Range("C3")
Do While Not IsEmpty(target.Value)
Set target = target.Offset(1)
Loop
target.Value = source.Value
End Sub
Chip's suggestion that you learn the basics of VBA is a good one. If you are someone (like me) who learns through books better than with online tutorials, I would recommend almost anything by John Walkenbach -- I first learned to program Excel by reading an early edition of his "Excel VBA Programming for Dummies."