Insert Array formula in Excel VBA - vba

I recorded the array formula in order to put in VBA. Here is what I have after the recording. However, when I run the Macro, it just doesn't work.
Will it be because of the negative sign?
From Macro
Range("D3").FormulaArray = "=IFERROR(INDEX('RMS
Maint'!R1C[-2]:R3542C[-2],SMALL(IF(('RMS Maint'!R2C27:R3542C27=R1C2)*('RMS
Maint'!R2C13:R3542C13=R2C4)*('RMS Maint'!R2C21:R3542C21=""Late"")*ROW('RMS
Maint'!R2C1:R3542C1)=0,"""",('RMS Maint'!R2C27:R3542C27=R1C2)*('RMS
Maint'!R2C13:R3542C13=R2C4)*('RMS Maint'!R2C21:R3542C21=""Late"")*ROW('RMS
Maint'!R2C1:R3542C1)),ROW('RMS Maint'!R[-2]:R[3538])),1),"""")"
From Excel formula
=IFERROR(INDEX('RMS Maint'!C$1:C$3542,SMALL(IF(('RMS
Maint'!$AA$2:$AA$3542=$B$1)*('RMS Maint'!$M$2:$M$3542=$D$2)*('RMS
Maint'!$U$2:$U$3542="Late")*ROW('RMS Maint'!$A$2:$A$3542)=0,"",('RMS
Maint'!$AA$2:$AA$3542=$B$1)*('RMS Maint'!$M$2:$M$3542=$D$2)*('RMS
Maint'!$U$2:$U$3542="Late")*ROW('RMS Maint'!$A$2:$A$3542)),ROW('RMS
Maint'!1:3541)),1),"")
The error is 1004 - Unable to set the FormulaArray property of the Range class
I'm sorry for the code format. It looked terrible.

Or you may break the long formula into few parts and replace it in the end with the actual formula like below...
Dim LogicalTest As String, FalseValue As String
LogicalTest = "('RMS Maint'!$AA$2:$AA$3542=$B$1)*('RMS Maint'!$M$2:$M$3542=$D$2)*('RMS Maint'!$U$2:$U$3542=""Late"")*ROW('RMS Maint'!$A$2:$A$3542)=0"
FalseValue = "('RMS Maint'!$AA$2:$AA$3542=$B$1)*('RMS Maint'!$M$2:$M$3542=$D$2)*('RMS Maint'!$U$2:$U$3542=""Late"")*ROW('RMS Maint'!$A$2:$A$3542)"
Range("D3").FormulaArray = "=IFERROR(INDEX('RMS Maint'!C$1:C$3542,SMALL(IF(""LogicalTest"","""",""FalseValue""),ROW('RMS Maint'!1:3541)),1),"""")"
Range("D3").Replace """LogicalTest""", LogicalTest, LookAt:=xlPart
Range("D3").Replace """FalseValue""", FalseValue, LookAt:=xlPart

There is an option of last resort: Use a human.
Have the macro place the formula into the cell as a String and have the user complete the process:
Sub pinocchio()
Range("D3") = "'=1+2"
MsgBox "User: Make this into a real array formula"
End Sub

Related

Inserting Formula in Formula Bar

Anyone knows what's the problem with my code?
Sub reFormat()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Admin")
ws.Range("C21").Formula = "=""S4&""AA5&""AA6&""AA7&""AA8&""AA9&""AA10" 'returns applica-
tion defined or object-defined error
End Sub
And I want the output of this code to be: =S4&(AA5&AA6&AA7&AA8&AA9&AA10)
Thanks for the help!
Your formula is fundamentally invalid. The string evaluates to this:
="S4&"AA5&"AA6&"AA7&"AA8&"AA9&"AA10
Which isn't a valid Excel formula.
You have too many quotes. If these are cell references and your formula intends to concatenate them, and you want your string to evaluate to this:
=S4&(AA5&AA6&AA7&AA8&AA9&AA10)
Then you could just do this:
.Formula = "=S4&(AA5&AA6&AA7&AA8&AA9&AA10)"

Number format displayed differently in the formula bar and cell vba

I used ActiveCell.Numerformat= "(0)" . The value is displayed with brackets in the cell but the formula bar shows the value without brackets.
Because of the above problem, Instead of using Numberformat I appended the number with brackets
var= "(" & value & ")"
After writing the var to the cell it is displayed as -450 instead of (450)
Either of method does not work for me. Any help? I am confused with vba and excel formats.
Consider:
Sub Macro2()
ActiveCell.NumberFormat = """(""General"")"""
End Sub
or:
Sub Macro2()
ActiveCell.NumberFormat = """(""0"")"""
End Sub

Use VLOOKUP to pass cell reference to a public variable?

I have a userform that opens on cell change in a column.
That userform contains checkboxes, which all trigger a second userform with a text box which looks up a cell on a hidden sheet for its contents. (The checkbox that's ticked determines which cell the textbox looks for). The user then edits the box, clicks a button, and the new text is written back to the same cell.
This is the VBA for when the checkbox is ticked. It works great. Hooray!
Dim vln As Variant
Dim reta As Worksheet
Set reta = ActiveWorkbook.Sheets("RetailerActivity")
Set vln = ActiveCell.Offset(-1, -3)
UserForm2.TextBox1.Text = Application.WorksheetFunction.VLookup(vln, reta.Range("A1:Z100"), 3, False)
UserForm2.TescoSave.Visible = True
UserForm2.Show
End Sub
When the textbox has been edited, I would like to write it back to the same cell it came from. I figure the easiest way to do that is to have a public variable (as range), and to pass the result of the vlookup into that variable so the second userform can have a line which reads
Private Sub ASave_Click()
publicvariable.Value = TextBox1.Value
userform1.hide
End Sub
Nice and easy, rather than doing a VLookup again. Right?
Either way, I can't seem to set the public variable as the lookup.
Outside of any sub I have
Public bums As Range
And in the code above, after the bit where I've set the text box, I've tried to add the line
Set bums = Application.WorksheetFunction.VLookup(vln, reta.Range("A1:Z100"), 3, False)
But the code errors with a "type mismatch".
If I try
Set bums = Range(Application.WorksheetFunction.VLookup(vln, reta.Range("A1:Z100"), 3, False))
I get method "Range" of object "_global" failed.
I code by cobbling bits off the internet, as you can probably tell, so this is I don't doubt a complete kludge.
Any advice would be super appreciated.
VLookup returns a value, not a Range. You could use Match to find the row and then Cells to get the actual reference - for example:
Dim vMatch
vMatch = Application.Match(vln, reta.Range("A1:A100"),0)
If Not IsError(vMatch) then
Set bums = reta.Cells(vMatch, "C")
else
msgbox "No match for " & vln
Exit Sub
End If
Personally I would also not use a public variable, but create a property for Userform2 to which you can assign the range.

How do I change the text of a cell without changing the formula?

I am new to VBA. This question has been asked and answered here but the answer seems way too hackish. Is there a better way to change the value of a cell without changing the underlying formula in it? I've tried target.text="changed" but that gives me an error of "Object Required"
The reason I ask is that in a UDF you can change the display of the cell but the formula remains there. How can I do this outside of a UDF?
EDIT:
In the example below, myudf and my_udf appear to do the same thing and everyone is telling me to just do NumberFormat. The problem is that Numberformat will change the cell permanently. If you entered "=my_udf()" in A2 then just go back and type some random text there. Unless you go back and manually re-format the cell (or enter in an excel built-in function), it will display "ThisThatThere".
Module1
Function myudf()
myudf = "ThisThatThere"
End Function
Function my_udf()
my_udf = "Temporary"
End Function
ThisWorkBook:
Sub Workbook_SheetChange(ByVal sh As Object, ByVal target As Range)
If target.HasFormula Then
If LCase(target.Formula) Like "=my_udf(*" Then
target.NumberFormat = "0;0;0;""ThisThatThere"""
End If
End If
End Sub
It is easy if the formula returns a number value rather than a text value .Place a formula in a cell, select it and run:
Sub ChangeText()
Dim DQ As String, mesage As String
DQ = Chr(34)
mesage = DQ & "override" & DQ
ActiveCell.NumberFormat = mesage & ";" & mesage & ";" & mesage & ";"
End Sub
By itself, a UDF , like a non-VBA worksheet formula, can only return a value to a cell.................the best the value can do it to affect conditional formatting.

Switch off R1C1 reference style for recorded VBA macros

In recorded VBA macros, it seems that their formulas use R1C1 reference style. For instance, to fill in B4 with B2+1:
Range("B4").Select
ActiveCell.FormulaR1C1 = "=R[-2]C+1"
Does anyone know if it is possible to switch off this mode? For instance, let recorded macro look like:
Range("B4").Select
ActiveCell.Formula = "=B2+1"
I believe you cannot do that. The macro will always record in R1C1 style.
You can always switch the style but it will only be applied to the worksheet and if you record a macro it will still show R1C1 reference style.
It is very easy to understand the R1C1 style
In R1C1 reference style, the range is referred by how far the cells are located from the cell you are calling. For example, if you have 5 values from R1C1 to R5C1 and the range is called from R7C2, then the range would be R[-6]C[-1]:R[-2]C[-1]. Here the first cell in the range is 6 rows before the cell R7C2 and 1 column before the cell R7C2 and similarly for the last cell in the range.
If I take your example then "=R[-2]C+1" means that the formula is referring to a row which is two rows up (-2) and in the same column (0). Your formula is same as "=R[-2]C[0]+1"
EDIT
Here is a small function that I wrote which can help you convert R1C1 to A1 string
Sub Sample()
'~~> This will give you $B$2
Debug.Print R1C12A1("B4", "R[-2]C")
'~~> This will give you E227
Debug.Print R1C12A1("O9", "R[218]C[-10]", True)
'~~> This will give you $Y$217
Debug.Print R1C12A1("O9", "R[208]C[10]")
End Sub
Function R1C12A1(baseCell As String, sRC As String, Optional RemDollar As Boolean = False) As String
Dim MyArray() As String
Dim r As Long, c As Long
sRC = Replace(sRC, "R", "")
If Left(sRC, 1) = "C" Then
r = 0
Else
r = Replace(Replace(Split(sRC, "C")(0), "[", ""), "]", "")
End If
If Right(sRC, 1) = "C" Then
c = 0
Else
c = Replace(Replace(Split(sRC, "C")(1), "[", ""), "]", "")
End If
If RemDollar = False Then
R1C12A1 = Range(baseCell).Offset(r, c).Address
Else
R1C12A1 = Replace(Range(baseCell).Offset(r, c).Address, "$", "")
End If
End Function
Note: I have not done any error handling here. I am sure you can incorporate that if needed.
There used to be a facility to toggle relative reference when recording a macro.
When you have started recording, in the macro toolbar - near the stop button - there was a button to toggle relative reference; is this not the same as toggling R1C1 ? or isn't this available anymore?
I never bothered toggling it myself as like Siddharth says the R1C1 isn't too tricky to understand plus, irrespective of whatever you do, the VBA will need some editing so at the same time if you wish to use other syntax it's easy enough to change.
I've just played around with the following but it doesn't seem to help so maybe I'm mixing up the use of this button with R1C1...