Adding more information to a pre-exsting cell formular - excel

I belive that this is possible with my limited knowldge of vba. I am trying to add more information to a pre-exsiting formula within a workbook.
Currently the formula is as follows, in Cells(SnapshotStartRow-2,11) the formula is =SUM('GK034'!B5 + 'GK034'!B21 + 'GK034'!B34)
The next stage is add an extra cell addition to the equation to look like
=SUM('GK034'!B5 + 'GK034'!B21 + 'GK034'!B34+ 'GK034'!B50)
My idea was to use this code below;
With Worksheets("Snapshot")
sAddress1 = .Cells(SnapshotStartRow - 2, 11).Address(0, 0)
End With
With Worksheets(SnapshotArray(i, 1))
sAddress2 = Worksheets(SnapshotArray(i, 1)).Cells(NewEngineRowNumber + 2, 2).Address(External = True)
End With
With Worksheets("Snapshot")
sFormula = "=Sum(" & sAddress1 & "+" & sAddress2 & ")"
.Cells(SnapshotStartRow - 2, 11).Formula = sFormula
End With
Some info on this code,
SnapshotArray(i,1) is there a reference for finding the sheet and contain the value GK034
SnapshotStartRow is used to defined a previously needed row reference and is equal to 125.
NewEngineRowNumber is used to define a previously needed adrress and is equal to 48
The idea behind the code was to take the current formular and mearly add the new cell to it.
Howevver there were a few issue that I failed to forsee,
Firstly, the 1st with loop mearly took the value of the cell rather than the exsisting formular.
Secondly the equation failed to remember which sheets the data was taken from.
Once i ran the code I ended up with, in the correct cell (The only part of the code that worked)
= SUM(K123 + $B$50)
Where K123 is the correct cell that use to contain the formular and B50 is desired cell on a different worksheet.
However K123 is now 0 and $B$50 dosen't refer to the desired workbook.
If anyone is able to help me that would be greatly appriciated. I will keep updatingthe post as i try new methods.
having done some more resurch I belive I need to extract the current formula as a string, which I belive can be done with a function, below.
Function CellFormula(Rng As Range) As String
CellFormula = Rng.Formula
End Function
Then could you add to the string the new code `$b$50 with the correct worksheet, then somehow paste the new string into the formula bar? Is that even possible?
From QHar comments, I tried to concatenate the worksheet name using,
With Worksheets(SnapshotArray(i, 1))
sAddress2 = Worksheets(SnapshotArray(i, 1)).Name & .Cells(NewEngineRowNumber + 2, 2).Address(External = yes)
End With
This didn't work either and noticed that parts of the equation were missing, I tried to add them manually and this failed to work, see below.
With Worksheets(SnapshotArray(i, 1))
sAddress2 = "'" & Worksheets(SnapshotArray(i, 1)).Name & "'!" & .Cells(NewEngineRowNumber + 2, 2).Address(External = yes)
End With

Related

Extract text string from another cell formula problem

I’m currently trying to include a VBA code into a larger Macro however one particular line (in Part B) is throwing out an error with the FIND function. The objective of the code is to insert two formulas into two diiferrent cells that extract text string from other cell (this formula is copied down accordingly). Below is what I have to date
' Part A
x = Range("A" & Rows.Count).End(xlUp).Row
sConc = "=B2&"" - ""&XLOOKUP(B2,Table4[Code], Table4[Description])"
Range("J2").Resize(x - 1).Formula = sConc
' Part B
y = Range("B" & Rows.Count).End(xlUp).Row
sConc = (LEFT(G1,FIND(" - ",G1)+1)) ' THIS LINE
Range("K2").Resize(y - 1).Formula = sConc
I gather the FIND function will not work within VBA and I need to use the INSTR function however I cannot figure out how to extract the required text ( before the " - ") from the cell using the INSTR function.
Any help on this would be greatly appreciated
Thanks

Dynamic Column Index Name Error in Formula

I am trying to calculate the component q'ty from Sheet Plan to Sheet Result by using Vlookup to fill in column,having:
Count_col: is the total column in sheet Plan
Last_col: is the total column in sheet Result (before add column Demand)
Sheet Results
Material
Component
Demand W1
Demand W2
ABCD1000
nc200
#NAME?
#NAME?
Sheet Plan
Material
Demand W1
Demand W2
ABCD1000
1000
200
For i = 1 To count_col
Cells(1, i + last_col).Value = "=Plan!RC[-2]"
Cells(1, i + last_col).Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC1,Plan!C1:C15,i+1,0)"
Next i
But the result is name error, I checked the spelling of function is correct and dont know how to fix. Why there is "#" in my formula?
Detail of error
=VLOOKUP($A2,Plan!$A:$O,#i+1,0)
i+1 inside "" behaves like a string rather than a variable. Try this.
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC1,Plan!C1:C15," & i + 1 & ",0)"
Also avoid the use of .Select. Your code can be written as
Cells(1, i + last_col).Offset(1, 0).FormulaR1C1 = _
"=VLOOKUP(RC1,Plan!C1:C15," & i + 1 & ",0)"
Recommended Reading: How to avoid using Select in Excel VBA
Also you are mixing R1C1 and A1 style of referencing. I would recommend using one of them. A simple Google search R1C1 vs A1 style will explain what they are.
In R1C1, Plan!C1:C15 needs to be written as Plan!R1C3:R15C3. So your final code would be
Cells(1, i + last_col).Offset(1, 0).FormulaR1C1 = _
"=VLOOKUP(RC1,Plan!R1C3:R15C3," & i + 1 & ",0)"

Copying a Range from one Sheet to Another with Variables

This is my code:
If AssociateNameArray(ArrayLoop) = ThisWorkbook.Sheets(i).Cells(3, CompareCounter).Value Then
If i = 2 Then
Sheets(i).Range(CompareCounter & "6:" & CompareCounter & "12").Copy Destination:=Sheets(1).Range((ArrayLoop + 4) & "2")
Sheets(i).Range(CompareCounter & "14:" & CompareCounter & "28").Copy Destination:=Sheets(1).Range((ArrayLoop + 4) & "9")
CompareCounter = CompareCounter + 1
End If
End If
It gives
1004 error
Basically I am walking through a set range where CompareCounter is the column number. (stupid name, I know) I have names in an array and it is comparing the values of the array to cells in a row and when it finds a match it copies a set range back to the person's column on the main page at a certain row. The person's column number should be ArrayLoop + 4, as they start in column E. I will walk through each sheet (i) and when I find matches I will take the ranges from that sheet and copy it to the main page.
This is what causes the 1004 error: Range((ArrayLoop + 4) & "2")
If ArrayLoop is 4, then once it is evaluated to something, then it looks like this Range(52) and this is no valid range, returning 1004.
In general, try to debug the code step-by-step with F8 and always look at the values of the variables.

Preventing subtraction to appearing in formula bar (Excel 2010, VBA)

Seeking help!
Hi,
I am almost done on a project and there's a part I don't understand
I have a + and a - button to add amounts from it's left cell to a total cell on the right (reads 54 in the example) (shown in the link down below)
Also, the amount of times the + is pressed is also calculated on the far most cell (2 for this example)
From the following code I made:
Range("L8").FormulaLocal = "=" & Replace(Range("L8").FormulaLocal, "=", "") & "+" & Range("G8")
The problem is that with the same code, using subtraction, I don't want to see it in the formula bar as it ends up as:
=29+29+29-29-29+29... (2nd image)
I only want to keep the positives. Is there something in the above mentioned code that I can change that will not show the subtraction though and not erase the whole formula that is there already
Thanks!
Part of my excel sheet for better understanding:
What I don't want to see in my formula bar:
First, shouldn't the value in your screenshot be 58, not 54?
Next, does the cell really need to contain a formula? As #teylyn mentioned, just do the calculation in VBA and set the cell's value. E.g. for the + button:
Range("L8").Value = Range("L8").Value + Range("G8").Value
Finally, if you really need to keep the formula, and you know that the value in cell G8 (the value being added or subtracted) never changes between clicks of the + and - buttons, you could first increment the counter (which I assume is cell M8), and then use its value to build the formula.
That might look something like the following, although you'd want to add some error trapping. Also, if you can ensure the counter will never be negative, you could eliminate the ElseIf portion:
Public Sub MinusButton_Click()
Range("M8").Value = Range("M8").Value - 1
Range("L8").FormulaLocal = GetCellFormula
End Sub
Public Sub PlusButton_Click()
Range("M8").Value = Range("M8").Value + 1
Range("L8").FormulaLocal = GetCellFormula
End Sub
Private Function GetCellFormula()
Dim strFormula As String
Dim intNum As Integer
strFormula = "="
If Range("M8").Value > 0 Then
For intNum = 1 To Range("M8").Value
strFormula = strFormula & Range("G8").Value & "+"
Next intNum
ElseIf Range("M8").Value < 0 Then
For intNum = Range("M8").Value To 1 Step -1
strFormula = strFormula & Range("G8").Value & "-"
Next intNum
End If
strFormula = Left(strFormula, Len(strFormula) - 1) 'strip trailing symbol
GetCellFormula = strFormula
End Function
Otherwise, if the value in cell G8 may change, your only option may be to do some (potentially) complicated parsing of the existing formula. If that's the case, please give it a try first, and post a new SO Question if you have any issues.

Calculating Cell Addresses in Formula with Row() and Column() in MS Excel VBA

I have gotten so much excellent help from this site. This is my first question. I have googled all the wordings I can think of and looked at all possible related threads on this site and others, and cannot find an explanation.
I am trying to automate a sheet into which a data table of variable size will be pasted.
Here is the formula I am trying to replicate:
=(C26-B26)/B26 (percent variation to previous month)
Edited to respond to a comment: This formula is in cell C28 in the sheet I am being asked to automate. So it is referring to cells two rows above and 1 column to the left of the cell where the formula is located.
Here is my code which the editor accepts:
ActiveCell.Formula = "=(" & (Cells(Index(Row() - 2), Index(Col())).Address(False, False)) & "-" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & "/" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & ")"
When I run this, I get a compile error: Sub or Function not defined and the first instance of row is highlighted.
It seems to me I read somewhere that one cannot calculate with Row() and Column() but I have not been able to find that again. I have found many examples online of people using Row() and Column() in this way to find cells adjacent to the active cell.
I appreciate any help and suggestions.
Thank you in advance.
I'd determine the indices of your reference cell (the one that's not known). In the example below, I'm simply using the indices and converting them to characters from ASCII and concatenating the returned character and the row number.
Dim activeRow, activeColumn As Integer
activeRow = 40 'Iterate through or use Range reference as Range.Row
activeColumn = 3 'Iterate through or use Range reference as Range.Column
MsgBox ("=(" & Chr(64 + activeColumn) & (activeRow - 2) & "-" & Chr(64 + activeColumn - 1) & (activeRow - 2) & "/" & Chr(64 + activeColumn - 1) & (activeRow - 2) & ")")
Update:
Also take a look at this question for referencing the instance of the calling cell in a Public Function, specifically Fionnuala's answer.

Resources