Copy Formula to a range - vba

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.

Related

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/Excel - cells not recognised as blank until I select and press enter

I have a macro which generates an output sheet to drop into a purpose-built (in C#) application for processing sheets of this type.
Essentially, the code copies one of the sheets from the master sheet and then saves it using a user-generated reference. It then copies and pastes all of the cells in the sheet as values.
Very frustratingly, in two of the columns in the output sheets, the cells with numbers in them are interspersed with supposedly non-blank cells which do not contain any characters or spaces (and are formatted as "general"). When I use an "IsBlank" formula, these return "FALSE". However, if I manually click on the cells in question and press "enter", these suddenly return a "TRUE" value.
I am considering getting the macro to select every cell in these columns one by one to resolve this, but that seems criminally inefficient.
Is there a better solution to this problem?
If ISBLANK formula is returning "FALSE", but hitting F2 + Enter return the same as "TRUE", then check if formulas => Workbook calculation is set as "Manual".
Also, data copied from external source may contain non-breaking space, with which Excel often struggles.
If clicking the cell is the only thing that works, you may add a small piece of code block like this, which'll refresh the selected range:
Sub refresh()
Dim r1 As Range, r2 As Range
Set r2 = Selection
For Each r1 In r2
r1.Select
Application.SendKeys "{f2}{enter}"
DoEvents
Next
End Sub
What you might be experiencing are zero length strings.It may have been the result of a formula which evaluates to "" (e.g. ="") and then copied and pasted as values.
As I understand, you are using macro. If that is the case, you use AutoFilter method of Range Object to get all non-blank cells. Something like:
Dim r as Range
Set r = Sheet1.Range("Your Range") '/* from your master sheet */
'/* Filter all non-blanks */
'/* First argument 1 depends on the column you want filtered */
'/* For this example it is column 1 of your range */
r.AutoFilter 1, "<>"
r.SpecialCells(xlCellTypeVisible).Copy
Sheet2.Range("Your Destination").PasteSpecial xlPasteValues
Hope this helps.

Excel VBA - transpose formulas in vertical array to horizontal array

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

Formula to remain after running macro

I was wondering how I can have a formula stay on column J2:J600. The formula is =R2 and would go all the way down to =R600. I thought I could manually put the formula in but every time I run my macro, the formulas disappear. Is there a way to embed the formula into the column? Thanks.
EDIT
Sub FormatCounsel()
Sheet2.Range("J2").FormulaR1C1 = "=RC[0]"`
Sheet2.Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault
End Sub
This is what I put in and I'm getting an error.
EDIT 2
Sorry I just realized that I want the formula =R2 in cells J2:J600. Sorry if I caused any confusion.
I see a big red flag in your code: you're using circular referencing! This means that you're saying J2 = J2. In other words, your formula refers to itself for a value, so it calculates to find the value, but to find the value it needs to calculate, etc...
Entering circular referencing should always give you an error when you manually enter circular referencing. However, when using VBA to enter the CR, I was only able to raise an error by setting Application.Calculation to xlCalculationManual, and then calculating the sheet.
You may have just made a typo, and that explains why there's circular referencing in your code, but I figured I'd explain it anyway. :)
R1C1 formulas use relative references to refer to cells. So when you say RC[0], you're saying that you want to use the cell in the same row and the same column. Let's see some examples. In our example, the formula will be in B2.
Dim r As Range
Set r = Range("B2")
r = "=RC" '<~~~ the equivalent to what you used in your code. Refers to B2.
r = "=R[-1]C" '<~~~ Refers to B1 (current row minus 1).
r = "=RC[1]" '<~~~ Refers to C2 (current column plus 1).
r = "=R[1]C[1]" '<~~~ Refers to C3 (current row and current column plus 1).
r = "=R[-1]C[-1]" '<~~~ Refers to A1 (current row and current column minus 1).
Now, as far as entering formulas into cells, it can be done all at once and very easily. Consider the example below:
Sub FormatCounsel()
Sheet2.Range("J2:J600") = "=RC[1]" '<~~ Each cell will refer to the cell to the right.
End Sub
Any time you write something else to those cells or clear them with the macro, you will lose those formulas. You need to find the place in your code where you are overwriting or clearing them, and modify that code. The other option is writing those formulas back to the cells at the end of the macro. You can accomplish this with:
Range("J2").FormulaR1C1 = "=RC[0]"
Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault

Paste text as formula

I am creating a string that is a formula. Like in here (this is a simpler example)
If:
A1 is "Sum"
A2 is "D3"
Then B1 is =Concatenate("=",A1,"(",A2,")")
I want a VBA macro that takes the result of the formula in B1 and paste is as a formula in C1.
I need C1 to be the formula =SUM(D3)
I think it involves the PasteSpecial and evaluate, but I can't figure out how.
I don't want to use the INDIRECT function because I want to be able to fill more cells using than formula and the relative references inside.
with Activesheet
.Range("C1").Formula = .Range("B1").Value
End With
I don't know if you explicitly want a command macro, but this thing seems like a great use of a VBA UDF. If you create the UDF:
Function EvalFormula(f As String) As Variant
EvalFormula = Application.Evaluate(f)
End Function
Then in C1 you can call:
=EvalFormula(B1)
Writing this as a UDF is going to eliminate those unpleasant situations where you forgot to run your macro and now your sheet is all out of whack.
I used ActiveSheet.Cells(5, 3).Formula = ActiveSheet.Cells(5, 3).Value to use the text value as a formula
ActiveSheet.Cells(2, 2).Value = ActiveSheet.Cells(1, 2).Value
You can work the rest from that I'd assume :-)