VBA to assign a cell content as a formula not its results - vba

I'm trying to assign a cell a formula using VBA, but every time I run the code it assign to the cell the result not the formula itself, like when I enter the formula using the excel spreadsheet.
Does anyone know how to display the formula using a macro within a cell and not the formula result.
I'm asking this because I need to insert this line within an existing sheet among other data and then run another macro to keep it updated, and the macro depends on this formula.
The code I'm using
Cells(C, 9).Formula = Application.Index(Plan2.Range("B2:D10000"), _
Application.Match(Plan1.Range("B" & C) & Range("F" & C), Plan2.Range("A2:A10000"), 0), 3)
As you can see this formula depends on the row that its inserted.

Your Formula is ultimately being reduced to whatever is returned by Application.Index. Unless the value being returned there is an actual formula string then you will just get a number as the result and this is set to the .Formula.
If you want to actually set the formula, you need to create a string in VBA that represents the formula to use. In this case, that string would look something like:
Cells(C, 9).Formula = "=INDEX(Plan2!B2:D10000, MATCH(Plan1!B" & C & "..."
where you concatenate in the dynamic parts. The end result needs to look like a normal formula. The Application.XXX and Application.WorksheetFunction.XXX functions return actual results, not pieces that can be combined to create a formula.

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.

Creating an absolute, yet variable, reference in VBA

First time poster here, I've been searching for the last hour without success so I'm turning to asking for help... My limited VBA knowledge might be a factor here.
I'm creating a quick macro that will sum values cumulatively. I regularly use =SUM($A$2:A2) and AutoFill down to get a cumulative sum. While I can be very quick at doing this, I have to do it several times per day in various sheets. My goal was to have the absolute $A$2 reference to be variable based on the current selected cell.
So let's assume I am trying to add this formula to cell B2. I know I can do:
ActiveCell.FormulaR1C1 = "=SUM(R2C1:RC[-1])"
However, this formula is unusable if my starting cell is anything but B2 and I am trying to cumulatively sum data in various columns.
Is it possible to have VBA count the number of columns between the selected cell and A2 and use this as a variable to set the absolute reference? Such as:
ActiveCell.FormulaR1C1 = "=SUM(R2Cvar:RC[-1])"
where var is =COUNTA(R2C1:ActiveCell)+COUNTBLANK(R2C1:ActiveCell)-1
I know the above code isn't valid, but it's the only way I can think of explaining what I'm trying to achieve.
You'll have to concatenate your formula eg
ActiveCell.FormulaR1C1 = "=SUM(R2C" & var & ":RC[-1])"
But to get your variable you can do
var = (ActiveCell.Column - 1)
Something like:
Sub ytrewq()
Dim s As String
With ActiveCell
s = .Offset(0, -1).Address(0, 0)
.Formula = "=SUM($A$2:" & s & ")"
End With
End Sub
The Offset() generates the address of the cell "just to the left".

Writing formula into an Excel Range with Option Strict On

Is it possible to write formulas across a range in Excel from VB.Net? I'm using a String array to hold a list of formulas that I would like to apply to an Excel range, instead of looping through and writing them one at a time.
This line is what I am attempting to use to write to a range:
xlWorkSheet.Range("AF" & intCurrentRow.ToString & ":AG" & intCurrentRow.ToString).Formula = formulas
The formula is being written to Excel, but Excel is actually displaying the formula, instead of the calculated value. If I write each formula to each cell like this:
xlWorkSheet.Range("AF" & intCurrentRow.ToString).Formula = formulas(0)
xlWorkSheet.Range("AG" & intCurrentRow.ToString).Formula = formulas(1)
It works perfectly fine and Excel displays the calculated values as it should. Almost seems like I'm missing a step but I haven't been able to find anything in my research.
As soon as I hit post I figured out the problem. Instead of using the .Formula property of an Excel.Range, you have to use the .FormulaArray property instead.
xlWorkSheet.Range("AF" & intCurrentRow.ToString & ":AG" & intCurrentRow.ToString).FormulaArray = formulas

Using a variable in a range statement in VBA excell macro

Ok, I'm sure this question is really basic but all my searchers turn up complicated answers and I've been messing with VBA for about a day. I have two worksheets in an excel doc, I've created a button that I can click that invokes my macro that is just moving cells from one work sheet to another. But I need my macro to determine what row I am on. I'm using this:
r = ActiveCell.Row
to determine my row, but what would be the easiest way to use that variable in a range statement like this:
Range("A2").Select
You could use the Range method with the & operator to join the variable into a string:
Range("A" & r)
Alternately you can use the Cells method which takes arguments (Row, Column):
Cells(r, "A")

Add a cell formula in Excel via vba

I’m not an Excel or VBA expert but I want to insert this current excel formula into cell’s using VBA.
Current Excel formula:
=IF(OR(ISNUM(D570)=FALSE;ISNUM(D573)=FALSE);"";IF(C573="Total";D573-D570;""))
VBA formula :
ActiveSheet.Range("a" & ActiveSheet.Rows.Count).End(xlUp).Offset(2, 12).Value = "=IF(OR(ISNUM(R[-3]C[-9])=FALSE;ISNUM(R[0]C[-9])=FALSE);'';IF(R[0]C[-10]='Total';R[0]C[-9]-R[-3]C[-9];''))"
It doesn’t work… Someone can help me please?
Try using .formula = instead of .value = in your VBA code.
Setting the .value of a cell simply copies in whatever value you specify. In this case, your formula is simply converted to a string value.
Using the .formula property, you are actually specifying the formula that gets used to compute the value, which is what you are looking for.
Can I first suggest a simplification of your formula, from:
=IF(OR(ISNUM(D570)=FALSE;ISNUM(D573)=FALSE);"";IF(C573="Total";D573-D570;""))
...to...
=IF(AND(C573="Total"; ISNUM(D570); ISNUM(D573)); D573-D570; "")
Then, I'd set a cell (the active cell in the example below) to use that formula using the VBA code:
ActiveCell.Formula = "=IF(...)"