Using IF statement with variable row numbers in VBA - excel

I am attempting to place the following formula into a cell through VBA:
=IF('Other Sheet'!D2="", 'Other Sheet'!D1, 'Other Sheet'!D2)
I have replaced the row number with variables and am attempting to concatenate them together as the formula is repeated as part of a loop.
ActiveCell.Formula = "=IF('Other Sheet'!D" & Row2 "="""", 'Other Sheet'!D" & Row1 ", 'Other Sheet'!D" & Row2 ")"
The formula works without variables when pasted into a cell or when in a line as vba however when I attempt to split it up, I get either a syntax error or an expected end of statement error around the equal sign.
I am very new to VBA and only have about 2 weeks experience with it.
I have tried troubleshooting by breaking apart the if statement and changing the location of double quotes and adding the .Formula suffix but nothing seems to be working.
Ideally after concatenation the code would repeat for each loop increasing by 5
ie.
first pass =IF('Other Sheet'!D2="", 'Other Sheet'!D1, 'Other Sheet'!D2)
second pass =IF('Other Sheet'!D7="", 'Other Sheet'!D6, 'Other Sheet'!D7)

Almost there - missing a couple of &
ActiveCell.Formula = _
"=IF('Other Sheet'!D" & Row2 & "="""", 'Other Sheet'!D" & Row1 & ", 'Other Sheet'!D" & Row2 ")"

Kudos to Tim Williams. I just wanted to explain how I convert formulas into code.
Create a working formula in the ActiveCell
Print the Actual formula in the Immediate Window: ?ActiveCell.Formula
Print the test formula code in the Immediate Window: '?Replace(ActiveCell.Formula,Chr(34),String(2,34))'
Type ?" and the output of step 2.
Start building my formula
Shortcut keys:
Delete Line: Ctrl+y
Insert Line: Ctrl+Enter

Related

Inserting TextBox Values into a Formula

I was hoping you could help me find the solution to my macro coding.
The textbox values are not being entered into the formula when pasted into the active cell.
Here is my coding:
ActiveCell.Formula = “=“”BOX “”&IF(OR(M3=1,M3=3),N3+TextBox1,N3-TextBox1)”
I want the cells end result to look something like this: BOX 20
Thanks
Do not use those fancy quotes, as VBA does not understand them.
Variables cannot be inside of quotes, so use this instead:
ActiveCell.Formula = "=""BOX ""&IF(OR(M3=1,M3=3),N3+" & TextBox1 & ",N3-" & TextBox1 & ")"
Keep in mind that if your textbox has something other than a number in it, or it is blank, you will get an error.
If IsNumeric(TextBox1) Then
ActiveCell.Formula = "=""BOX ""&IF(OR(M3=1,M3=3),N3+" & TextBox1 & ",N3-" & TextBox1 & ")"
Else
MsgBox "'" & TextBox1 & "' is not a numeric value."
End If
If you compare my answer to your question, do you see how your formula is all red? That means it's all part of a literal string, so there are no variables in it, and since your textbox is a variable, it needs to be outside of the quotes.
In my code, see how the TextBox1 variable is not red?
Named Ranges and Control Settings Setup
Named Ranges
• Box
• SelectedFruit
• Fruit
Settings
• Textbox:
- LinkedCell = Box
• Combobox
LinkedCell
ListFillRange
The trick is to use Named Ranges and Control settings. No VBA required!

Concatenate date, text and cell value

I am trying to use VBA to create a description that includes the Month/Year, text, and the value of a cell. I have tried two methods and neither one is working for me.
First i tried this:
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Format(DateAdd("m", -1, now), "mmmyy"), " My Text ",RC[-19])"
Which gives a
run-time error 1004.
Next I tried
Range("X10").Value = Format(DateAdd("m",-1,now), "mmmyy") & " My Text " & E10
Which output the date and the text but not the value of the cell.
I'm not sure where I'm going wrong with this. Searching on here got me to this point, but I'm stuck.
Thanks for any help.
'Let: X be your Workbook index, Y be your sheet index, YY be your row index, XX be your column index
Sub macro2()
MsgBox Month(Date) & "/" & Year(Date) & " " & Workbooks(X).Sheets(Y).Cells(YY, XX).Value
End Sub
All of these may be stored into a string variable for portability across your project.
Good luck!.

VBA If Statement Formula in a Loop and Range Function to Get Cell Value

I am trying to assign If formula to certain cell every 16th row. Formula needs to compare values of cells in J, K and L columns and gives Pass or Fail Result.
I am having issues making this If formula work in a loop. Please Help! My Code is below.
First I am getting compile error saying " Expected end of statement"
Second, is there any other way to make these work? I need same formula applied to Cell M5 to M789 at every 16th cell.
For a = 5 To 789 Step 16
Range("M" & a).FormulaR1C1 = "=IF(Range("J" & a)>= Range("K" & a),IF(Range("J" & a))<= Range("L" & a),""PASS"", ""FAIL""),""FAIL"")"
You need .Formula instead of .FormulaR1C1 - you are not using R1C1 references.
Remove the Range calls from the formula part. That's mixing VBA with regular worksheet formula syntax.
You can simplify the formula using AND. And in this case you don't need to concatenate a in at all. Excel is smart enough to update relative references.
Sub Test()
Dim myFormula As String
myFormula = "=IF(AND(J5>=K5,J5<=L5),""PASS"",""FAIL"")"
Dim a As Long
For a = 5 To 789 Step 16
Range("M" & a).Formula = myFormula
Next
End Sub

How to Trim Headings in a table with VBA code

I'm trying to trim the headings of a table with VBA code because some of them have spaces in front that varies every month, which makes it difficult for coding.
When I break down the code and run it step by step it works fine but when I run the whole macro it removes some of my headings and replace them with info from a different sheet row or just "column 1", "column 2", etc.
I believe I'm missing some code reference when it calls the (" & .Address & ") selection?
It's replacing the headings from a sheet where the cell is active. (If it was the last cell to click on before running the macro).
I've tried just using the Trim function, but because it's an array for the range, it doesn't work, and someone suggested to use the "evaluate" function.
I've tried using the trim function as a WorksheetFunction as well but it gave me an error "Run-time error 13" Type-mismatch". Which was on the following code:
With wsDispoData.ListObjects("Table_DispoData").HeaderRowRange.EntireRow
.Value = WorksheetFunction.Trim(.Value)
End With
This is the current code I'm using that replaces wrongly.
Trim headings
With wsDispoData.ListObjects("Table_DispoData").HeaderRowRange.EntireRow
.Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
End With
Expected results should be for example:
Current headings: " SOH" and " Compo"
Trimmed: "SOH" and "Compo"
I would just enumerate through the header row and check each value
Dim Cell As Range
For Each Cell In wsDispoData.ListObjects("Table_DispoData").HeaderRowRange
Cell.value = WorksheetFunction.Trim(Cell.value)
Next Cell

Adding a formula in VBA

I have created a code that adds a new line to my spreadsheet with the information that users enter into a user-form. The problem I'm having is that I have formulas in two of the columns that I need to be carried into the new rows. I have tried several different ways to do this but keep receiving an error message. The formula I need carries is
=IFERROR(INDEX(Equipment!$E$3:$E$1000,MATCH($B5&"-"&$A5,INDEX(Equipment!$B$3:$B$1000&"-"&Equipment!$A$3:$A$1000,0),0)),"")
The values that change line to line are the B and A cells after the MATCH command (in this case $B5 and $A5). Can anyone help me figure out how to convert this to VBA syntax so that I can add it to my code? Thanks in advance!
I Converted this formula, and tested it in a loop.
The formula is copied to Column D from rows 11 to 20, where $B5 and $A5 change according to whatever row they are (I hope I understand what you meant).
Sub ConvertFormula()
' modify to where (worksheet) you want to copy this formula
Set eqp_sht = ActiveWorkbook.Worksheets("Equipment")
' modify this according to whatever rows and column you want this formula copied
For i = 11 To 20
eqp_sht.Cells(i, 4).Formula = "=IFERROR(INDEX(Equipment!$E$3:$E$1000,MATCH($B" & i & "&-$A" & i & ",INDEX(Equipment!$B$3:$B$1000&-Equipment!$A$3:$A$1000,0),0))," & Chr(34) & Chr(34) & ")"
Next
End Sub

Resources