Forum Discussion
Riley Robinson
May 05, 2018Copper Contributor
Having VBA Macros upload a formula to a Cell
I'm trying to write a sub routine that identifies a last name from a cell in column B, insert that name into the formula to identify which tab the formula is supposed to work with and continue to do that for each row in a loop.
The routine I made makes the correct formula however, the formula only works as text. The coding is posted below. (I have used both Cells(I,3).Formula and Cells(I,3).FormulaArray but neither seems to work, please help?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim New_set As String
New_set = Range("A12")
Dim Hours
Dim Men As String
Hours = "=IF(Last!$B$6>0,(Last!$B$6-Last!$B$5)-SUM(Last!$B$7:$B$10),(IF(Last!$B$5="","",$C$1-Last!$B$5-SUM(Last!$B$7:$B$10))))"
If New_set = "Load Formulas" Then
For i = 13 To 17
Dim LastN
Dim p
LastN = Cells(i, 2)
p = Mid(LastN, 1, InStr(1, LastN, ",") - 1)
Cells(i, 3).FormulaArray = Replace(Hours, "Last", p)
Next i
End If
Range("A12") = " "
End Sub
It's difficult to tell exactly what you're trying to do without an example of how your worksheet is set up. Would it be possible for you to upload a non-sensitive mock up file with fake data in it, so that the community can better understand your scenario?
After skimming your code I noticed that this formula is incorrect:
Hours = "=IF(Last!$B$6>0,(Last!$B$6-Last!$B$5)-SUM(Last!$B$7:$B$10),(IF(Last!$B$5="","",$C$1-Last!$B$5-SUM(Last!$B$7:$B$10))))"
In VBA if you use double quotes like in a worksheet formula you actually need to repeat them 4 times. So your formula should look like this:
Hours = "=IF(Last!$B$6>0,(Last!$B$6-Last!$B$5)-SUM(Last!$B$7:$B$10),(IF(Last!$B$5="""","""",$C$1-Last!$B$5-SUM(Last!$B$7:$B$10))))"
- Matt MickleBronze Contributor
It's difficult to tell exactly what you're trying to do without an example of how your worksheet is set up. Would it be possible for you to upload a non-sensitive mock up file with fake data in it, so that the community can better understand your scenario?
After skimming your code I noticed that this formula is incorrect:
Hours = "=IF(Last!$B$6>0,(Last!$B$6-Last!$B$5)-SUM(Last!$B$7:$B$10),(IF(Last!$B$5="","",$C$1-Last!$B$5-SUM(Last!$B$7:$B$10))))"
In VBA if you use double quotes like in a worksheet formula you actually need to repeat them 4 times. So your formula should look like this:
Hours = "=IF(Last!$B$6>0,(Last!$B$6-Last!$B$5)-SUM(Last!$B$7:$B$10),(IF(Last!$B$5="""","""",$C$1-Last!$B$5-SUM(Last!$B$7:$B$10))))"
- Riley RobinsonCopper Contributor
I didn't notice that when it was inputting the formula, so it was working, I just didn't have it typed out correctly.
Thank you for that, I'll be sure to double check my coding a bit better.
- Matt MickleBronze Contributor
You're quite welcome. Something that has probably got the best of most of us at one time or another! I know it's happened to me a few times!
- Logaraj SekarSteel Contributor
Hi,
Put sample screen shot of excel.