Excel & VBA: Skip calculating formula in Macro - vba

I'm having a rather simple issue with Macro. In it, I assign a formula to a cell. I would like it not to calculate it at first and do calculation only after some other part of Macro is finished. I thought I would do something like this:
Application.Calculation = xlCalculationManual
Cells(StartRow, 4 + i).Formula = "FORMULA"
...
Application.Calculation = xlCalculationAutomatic
But that doesn't work. It stops automatic calculations, but not for that cell - it still performs the calculation right after I assign the formula. Is there a way to skip it?
To clarify the exact prupose of this: in my actual code I'm assigning a formula to a group of cells in a cycle. Everytime I assign it to one cell - it calculates it. I figured if I will first assign them all and then do the calculation - it would be faster. As a matter of fact it is. So instead of assigning it in a cycle, I assign it to the first cell and then do autofill. Autofilled formulas wait until I enable automatic calculation and I get a much faster macro. However, the initial assignemnt is still calculated which makes macro almost twice as slow.

place the formula in the cell with a prefix character
continue the macro
"activate" the formula
for example:
Sub dural()
With Range("A1")
.Value = "'=1+2"
MsgBox " "
.Value = .Value
End With
End Sub

#Alex, you can delay the calculation as #Gary answer. However, you was asking the question because you need "SPEED to CYCLE through cells" while assign a formula, right?
If yes, from my point of view, if you are NOT using the formulas until ALL the formulas are assigned in the excel sheet, you will gain a lot of speed by writing all the formulas at once using an array (a single step in VBA).
The procedure is: first put all the formulas to an VBA array of strings, and later on to use for example Range("B1:B100").Formula = ArrayWithFormulas. In that example you are assigning 100 formulas at once, without recalculation in between.
You will see a large improve in SPEED if use an array to write all the cells at ones instead of writing cell by cell! (Don't loop using cells(r,c+i) if you have a lot of cells to go through). Here one example:
Sub CreateBunchOfFormulas()
Dim i As Long
Dim ARRAY_OF_FORMULAS() As Variant 'Note: Don't replace Variant by String!
ReDim ARRAY_OF_FORMULAS(1 To 100, 1 To 1)
' For Vertical use: (1 to NumRows,1 to 1)
' for Horizontal: (1 to 1,1 to NumCols)
' for 2D use: (1 to NumRows,1 to NumCols)
'Create the formulas...
For i = 1 To 100
ARRAY_OF_FORMULAS(i, 1) = "=1+3+" & i ' Or any other formula...
Next i
' <-- your extra code here...
' (New formulas won't be calculated. They are not in the Excel sheet yet!
' If you want that no other old formula to recalculate use the old trick:
' Application.Calculation = xlCalculationManual )
'At the very end, write the formulas in the excel at once...
Range("B1:B100").Formula = ARRAY_OF_FORMULAS
End Sub
If you want an extra delay in the new formula, then you can use #Gary trick, but applied to a range, not to a single cell. For that start the formulas with a ' like '=1+2 and add the following code at the end:
'... previous code, but now formulas starting with (')
Range("B1:B100").Formula = ARRAY_OF_FORMULAS
'Formulas not calculated yet, until next line is executed
Range("B1:B100").Value = Range("B1:B100").Value ' <~~ #Gary's trick
End Sub
Last, a small snipped: if your formulas are in a horizontal arrangement (Means one formula for column A, other for column B, etc) and just a small number of columns, then you can keep in mind the a shorter version of previous code:
Dim a as Variant 'Note that no () needed
a = Array("=1+3","=4+8","=5*A1","=sum(A1:C1)")
Range("A1:D1").Formula = ARRAY_OF_FORMULA ' Just a single row
' or...
Range("A1:D100").Formula = ARRAY_OF_FORMULA ' If you want to repeat formulas
' in several rows.
Finally, You can use the method .FormulaR1C1 instead of .Formula in all the previous code examples, if you want an easy way to use relative references in your formula...
Hope this helps!

Related

Excel VBA - If cells is part of merged cells pass the value?

I'm having some trouble to prepare macro which would help me to pass the value to another cell if the specified cell is a part of merged cells.
As you can see, cells A1-A15 are merged, in B1 I've written =A1 in B2 I did =A2, so what I want to achieve is that whenever I assign somewhere cell which is part of merged cells(A1-A15) the 'test' value is passed so there is no difference if I write =A1 or =A15 or =A10
I would appreciate any help of advice.
You can detect if a Cell is part of a Merged Cell using If Range("A1").MergeCells = True.
Get the number of rows you have in your MergedArea using Range("A" & i).MergeArea.Rows.Count.
More explanation inside the code below.
Code
Option Explicit
Sub CheckifMergedCell()
Dim MergeRows As Long, i As Long
i = 1
While i < 100 ' 100 is just for example , change it later according to your needs
If Range("A" & i).MergeCells = True Then
MergeRows = Range("A" & i).MergeArea.Rows.Count ' number of merged cells
Else ' not merged >> single row
MergeRows = 1
End If
Range("B" & i).Resize(MergeRows, 1).Value = Range("A" & i).Value
i = i + MergeRows
Wend
End Sub
In B1,
=INDEX(A:A, MATCH("zzz", A$1:A1))
Fill or copy down.
what I want to achieve is that whenever I assign somewhere cell which is part of merged cells(A1-A15) the 'test' value is passed so there is no difference if I write =A1 or =A15 or =A10
What you want to accomplish can't be done easily. You could do it with an VBA code that checks every single time you type something, but it's not worth it. The other answer you got here are worth it.
What you want to do is not possible because Excel works in a weird way. Let's say you have cells A1:A15 merged. The value is ALWAYS in first cell of merged area (in this case in A1). So when you reference a cell inside the merged area, it will have a 0 value (a blank cell) always, unless it is the first one.
So my advice, would be:
Use 1 of the other answers, because both are really helpful
If you insist in using normal formulas, then instead of typing =A1, try with absolute references, try =$A$1. If you click and
drag, that formula will work for you to complete adjacent cells to
merged area.
I insist, use 1 of the other answers.

Do While ActiveCell <> Range

I have this VBA excel macro code
Sub fillcells()
Range("J14").Select
Do While ActiveCell <> Range("J902")
ActiveCell.Copy
ActiveCell.Offset(6, 0).Select
ActiveCell.PasteSpecial
Loop
End Sub
At first it was working fine but now sometimes when I try to run the macro the loop suddenly stops at cell J242, other times is arising an error 'mismatch type' and sometimes the macro just select cell J14 without doing the loop
Not sure what you want to do, but (as noted in the comments to your OP), don't use .Select/.Activate. The following should do what (I think) you wanted:
Sub fillcells()
Dim i& ' Create a LONG variable to count cells
For i = 14 To 901 Step 6
Cells(i, 10).Offset(6, 0).FormulaR1C1 = Cells(i, 10).FormulaR1C1
Loop
End Sub
This will loop from cell J14 to J901, copy/paste* to a cell 6 rows offset.
* Note I didn't actually copy/paste. Since your original code used PasteSpecial, I'm assuming you just want the values pasted. In this case, you can set the two ranges/cells equal.
Just an addition to what #BruceWayne already said: whenever you have this typical phenomenon that something happens only "sometimes" it is often a case of using keywords such as Active or Current or Selection. These are not specific but change each time that you call the macro. Whatever you have selected is the starting point. You might even start clicking around and thus change Selection while the macro is running. In short, you should start coding explicitly and don't allow VBA / Excel to assume / make the decision for you.
Let's start with Range("J14").Select. This line of code asks VBA to make already two assumptions:
If you have several Excel files open. Which Excel file should it start with?
Within the file there might be several sheets. On which of these sheets should J14 be selected?
Explicit coding means that you (hopefully at all times) be very specific what you are referring to. So, instead of just stating Range("J14") you should use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Range("J14")
But is pointed out in the other answer, this is not even necessary in this case. Rather loop the rows as shown and use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(6, 0).Formula = ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(i, 10).Formula
Since this is a bit lengthy you can shorting it by using a With statement:
With ThisWorkbook.Worksheets("SheetNameYouWantToReferTo")
.Cells(i, 10).Offset(6, 0).Formula = .Cells(i, 10).Formula
End With

Looping the whole cells to change a specific formula issue

I'm writing a function to change an entire column to new values using a formula, here's the code I'll elaborate more on the idea down there.
The problem is that it hangs and I have to rerun Excel and I'm not sure why.
Sub Button2_Click()
Dim i As Long
For i = 2 To Rows.Count
Cells(i, 4).Formula = "=B" & i & "+6*3600000/86400000+25569"
Next i
End Sub
So what's this about? I'm changing the fourth column to excel time because what I have in column B is epoch time, and this is the formula I'm using, it works with my case if I tried one by one, but for some reason it won't work as a whole. I'm not sure what's done wrong? But I'd appreciate your help.
Writing to cells one-by-one is very slow.
Writing formulas one-by-one is slower still, because each must be evaluated before Excel accepts them as formulas.
Doing this a million times can literally freeze Excel.
The solution is to write them all in one shot (no loops):
Sub Button2_Click()
[d2:d1048576] = "=B2+6*3600000/86400000+25569"
End Sub
' Another way of doing mass calculation is by using copy and paste method.
It will be better to convert the columns into values so that the sheet won't calculate again and again. It helps to prevent the sheet from hanging issues
Sub Button2_Click()
Range("D2").Formula = "=b1" & "+6*3600000/86400000+25569"
Range("D2").Copy
Range("D2:d1048576").PasteSpecial xlValues
Application.CutCopyMode = False
Range("D:D").Value = Range("D:D").Value
End Sub

Intersect not working if target range gets bigger

I am relatively new to VBA and I need help with this please.
I have a private sub within a sheet and I want it to autofill formulas adjacent to a dynamic named range, if the size of the range changes.
(edit) I am pasting data from another worksheet into this one columns A-M. My dynamic range is defined as =OFFSET($A$1,1,0,COUNTA($A:$A)-1,13). The first If statement should exit the sub if there is no data in column M and I had the destination calculating the last row of column M because I want to fill the formulas in N:O so that they cover the same number of rows as column M.
This is my code and it works if the size of the range gets smaller (i.e. if I delete rows from the bottom), but not if it gets bigger and I can't work out why!
Private Sub Worksheet_Change(ByVal Target As Range)
If Me.Range("M2").Value = "" Then
MsgBox "No Data!"
Exit Sub
Else
If Intersect(Target, Me.Range("rngOracleInvoices")) Is Nothing Then
Application.EnableEvents = False
Dim Lrows As Long
Lrows = Me.Cells(Me.Rows.Count, "N").End(xlUp).Row
Me.Range(Me.Cells(3, 14), Me.Cells(Lrows, "O")).ClearContents
Me.Range("N2:O2").AutoFill Destination:=Me.Range("N2:O" & Me.Range("M" & Me.Rows.Count).End(xlUp).Row)
End If
End If
Application.EnableEvents = True
End Sub
I put the last bit into a separate macro to test if it works on its own and for some reason, when I run it, the autofill goes all the way up to row 1 and overwrites the formulas, which is weird because I use that code a lot and it's never done that before. What have I done??!!
Also, if there is a better way to do the autofill I'd appreciate if someone could let me know what it is because I just cobbled that together from bits I found on forums :)
Thanks,
Soph
In this line Me.Range("N2:O2").AutoFill Destination:=Me.Range("N2:O" & Me.Range("M" & Me.Rows.Count).End(xlUp).Row) you calculate your last row on the column M so if it is empty it'll give you 1 and autofill your formula on row 1.
So start by calculating it on the good column (my guess is O)
You can also simply define an Integer variable to test it and if it is inferior to 2, change it back to 2, 3, 4 or whatever you want.
For your dynamic range, we might need some precision.
And for the AutoFill, you could just select manually the range N2:02 and then double-click on the bottom right square (the one you drag to autofill) and it'll autofill as long as there data in adjacent cells! (give it a try ;) )

VBA to insert and increment formulae in cell

I have this VBA
Sub ApplyCV()
Range("H2:H5000").Formula = "=GetPattern($A2)"
End Sub
Which basically applies the custom function "=GetPattern" to execute the macro of the same name. This works fine.
However, instead of explicitly stating the range (which will vary with each dataset) I'd like to increment the formula on a loop UNTIL the last row of data or until there is no cell value in A:whatever.
Any help with this would be gratefully received.
Many thanks
Try finding the last value in column A (looking from the bottom up) and using that cell's row to define the extent of the range in column H that the formula is applied to.
Range("H2:H" & cells(rows.count, 1).end(xlup).row).Formula = "=GetPattern($A2)"