Excel VBA .FormulaArray Error - vba

The error is a 1004 error but I don't understand why. The formula in the cell would be:
{=INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),37)+INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),38)-INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),39)}
To get this formula into a macro I simply used the recording tool but it did not work.
Selection.FormulaArray = _
"=INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),37)+INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),38)-INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),39)"

As long as you insist on doing things the hard way,
Option Explicit
Sub wqer()
With ThisWorkbook
.Worksheets("KPI").Name = "K"
.Worksheets("Monday").Name = "M"
'geez - decide what cell you want without Selection¹ !!??!!
Selection.FormulaArray = _
"=INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),37)+INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),38)-INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),39)"
.Worksheets("K").Name = "KPI"
.Worksheets("M").Name = "Monday"
End With
End Sub
Renaming your worksheets back and forth puts your formula under the built-in character limit² noted by Axel Richter for the time it takes to insert the array formula into the cell. This will put an undue calculation demand on your workbook but it may be an acceptable solution for you. Consider changing the application's calculation mode to manual for the duration of the operation.
.¹ See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.
² See Range.FormulaArray property.

You can also try this(
please don't run it from the VBE, try to run it from sheets environment. Go to Developer-Macros-Your Macro -Run or Run it from a button or shortcut and it will work without problem):
Selection.Formula = _
"=INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),37)+INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),38)-INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),39)"
SendKeys "{F2}"
SendKeys "^+{ENTER}"

Related

Run-Time Error '1004' in VBA Subroutine

There seems to be something wrong with one of my Excel Objects. Take a look at the below snippet. I created the subroutine Run_all(), and when I step through, it'll go up to the Function row_count() and start executing, however, when it gets to the first highlighted row, I get the error.
**The Sheet that I'm referencing in the function is typed correctly. For example, if I run the bottom subroutine CA_Copy_Paste_, it works correctly and I get no errors.
Why is Excel not recognizing "Sheet 3" in the function? For more context, it only works if I type "Sheet4". Does not work on "Sheet1" or "Sheet2" either.
If you insist on using .Select and .Activate to accomplish your goals then you must activate the worksheet before activating or selecting a cell or range of cells on that worksheet.
worksheets("sheet 3").activate
activesheet.range("c4").activate
If you wish to use some 'shorthand' to try and accomplish this in a single line of code then switch to the Application.GoTo method.
Application.Goto reference:=worksheets("sheet 3").range("c4")
In any event, you are best off avoiding the use of select and activate. See
How to avoid using Select in Excel VBA.

Do While ActiveCell <> Range

I have this VBA excel macro code
Sub fillcells()
Range("J14").Select
Do While ActiveCell <> Range("J902")
ActiveCell.Copy
ActiveCell.Offset(6, 0).Select
ActiveCell.PasteSpecial
Loop
End Sub
At first it was working fine but now sometimes when I try to run the macro the loop suddenly stops at cell J242, other times is arising an error 'mismatch type' and sometimes the macro just select cell J14 without doing the loop
Not sure what you want to do, but (as noted in the comments to your OP), don't use .Select/.Activate. The following should do what (I think) you wanted:
Sub fillcells()
Dim i& ' Create a LONG variable to count cells
For i = 14 To 901 Step 6
Cells(i, 10).Offset(6, 0).FormulaR1C1 = Cells(i, 10).FormulaR1C1
Loop
End Sub
This will loop from cell J14 to J901, copy/paste* to a cell 6 rows offset.
* Note I didn't actually copy/paste. Since your original code used PasteSpecial, I'm assuming you just want the values pasted. In this case, you can set the two ranges/cells equal.
Just an addition to what #BruceWayne already said: whenever you have this typical phenomenon that something happens only "sometimes" it is often a case of using keywords such as Active or Current or Selection. These are not specific but change each time that you call the macro. Whatever you have selected is the starting point. You might even start clicking around and thus change Selection while the macro is running. In short, you should start coding explicitly and don't allow VBA / Excel to assume / make the decision for you.
Let's start with Range("J14").Select. This line of code asks VBA to make already two assumptions:
If you have several Excel files open. Which Excel file should it start with?
Within the file there might be several sheets. On which of these sheets should J14 be selected?
Explicit coding means that you (hopefully at all times) be very specific what you are referring to. So, instead of just stating Range("J14") you should use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Range("J14")
But is pointed out in the other answer, this is not even necessary in this case. Rather loop the rows as shown and use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(6, 0).Formula = ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(i, 10).Formula
Since this is a bit lengthy you can shorting it by using a With statement:
With ThisWorkbook.Worksheets("SheetNameYouWantToReferTo")
.Cells(i, 10).Offset(6, 0).Formula = .Cells(i, 10).Formula
End With

Looping the whole cells to change a specific formula issue

I'm writing a function to change an entire column to new values using a formula, here's the code I'll elaborate more on the idea down there.
The problem is that it hangs and I have to rerun Excel and I'm not sure why.
Sub Button2_Click()
Dim i As Long
For i = 2 To Rows.Count
Cells(i, 4).Formula = "=B" & i & "+6*3600000/86400000+25569"
Next i
End Sub
So what's this about? I'm changing the fourth column to excel time because what I have in column B is epoch time, and this is the formula I'm using, it works with my case if I tried one by one, but for some reason it won't work as a whole. I'm not sure what's done wrong? But I'd appreciate your help.
Writing to cells one-by-one is very slow.
Writing formulas one-by-one is slower still, because each must be evaluated before Excel accepts them as formulas.
Doing this a million times can literally freeze Excel.
The solution is to write them all in one shot (no loops):
Sub Button2_Click()
[d2:d1048576] = "=B2+6*3600000/86400000+25569"
End Sub
' Another way of doing mass calculation is by using copy and paste method.
It will be better to convert the columns into values so that the sheet won't calculate again and again. It helps to prevent the sheet from hanging issues
Sub Button2_Click()
Range("D2").Formula = "=b1" & "+6*3600000/86400000+25569"
Range("D2").Copy
Range("D2:d1048576").PasteSpecial xlValues
Application.CutCopyMode = False
Range("D:D").Value = Range("D:D").Value
End Sub

VBA Concatenating columns from same worksheet in Range

I am having trouble concatenating two columns (variable range) to another column in the same document. Is there something really obvious I'm missing?
Function ConcCol(ConVal_1 As String, ConVal_2 As String)
Range("V30:V500").Select
Application.CutCopyMode = False
With ActiveCell
.FormulaR1C1 = "=CONCATENATE(RC[5],"" "",RC[6])"
End With
Selection.AutoFill Destination:=Range(Destination), Type:=xlFillDefault
End Function
When running the above function, I get the following error:
Error: Run-time error '1004': AutoFill method of Range class failed
I assume it's something to do with only one cell being activated perhaps? My VBA knowledge is limited
Sub ConcCol()
Range("V3:V500").Select
For Each Cell In Selection
Cell.Value = "=CONCATENATE(RC[5],"" "",RC[6])"
Next Cell
End Sub
I think it'd be easier (if you're going with the selection idea), to just use each cell. I think your with statement doesn't want to loop at all, hence error. This works, a simple solution.
I think this is what you're looking for:
Sub tgr()
With Intersect(ActiveSheet.UsedRange.EntireRow, Range("V30:V" & Rows.Count))
.Formula = "=AA" & .Row & "&"" ""&AB" & .Row
End With
End Sub
Hey I think you are a bit confused. How do you plan to run this code? You need to provide more details. Here are three ways of running a vba code:
User Interface as a User Defined Function (UDF)
As a Function that is called/used by another VBA code
AS a macro and user need to run it from the macro list
For your purpose, why doesn't the user use CONCATENANTE function in the sheet and fill down?
Maybe use the Excel array functions?
I cannot post images, need 10 reputations :s

Excel VBA: Formula is too complex for object

This may seem like a simple problem, but it's been very frustrating. I've written a couple (relatively simple) macros in VBA for a spreadsheet that I want to make very user-friendly.
In other words, I want all macros to be run by buttons. However, whenever I try to assign buttons to macros I am getting the error:
Formula is too complex to be assigned to object
This happens even when I try to assign it to an empty subroutine. It worked, but only for the first macro I wrote. Once I added other subroutines to the module, I could no longer assign new buttons to macros.
This is the code I've written:
Sub Button1_Click()
selName = Range("C2").Value
div = Range("E2").Value
cost = Range("F2").Value
diff = div - cost
If diff < 0 Then
diff = 0
End If
Range("G2").Select
ActiveCell.FormulaR1C1 = diff
x = Range("A2").Value + 1
Worksheets("VIP_TEMPLATE.PIVOT").Select
Range("J" & x).Select
ActiveCell.FormulaR1C1 = diff
Worksheets("CALCULATE").Select
Range("F2").Select
ActiveCell.ClearContents
End Sub
I have another subroutine in the module, which I think may be contributing to the problem? I think this because when I simply copy-pasted my data into a new worksheet, I could assign a button to the routine. I don't think it has anything to do with my file path because I don't use any (I think) offending characters.
I have found the problem. It turns out that I did actually have brackets in my file path (buried way in there).