Another >> Unable to set the FormulaArray property of the range class - vba

I've researched as many of the "Unable to set the FormulaArray property of the range class" issues here and in other sites to troubleshoot a FormulaArray operation I'm trying to carry out in a table of data.
I've respected the 255 character limit in my formula taking into account R1C1, I've tried to insert the formula as a text string first. I've tried quite a few things.
Now I'm thinking my issue is with the fact that I'm trying to insert my formula only into blank cells because if I simplify my formula to only be =1+1 I still get the error. If I change .FormulaArray to .Formula to simply enter a standard formula I also get the same error. Is this operation not possible with blank cells?
The error occurs at the .FormulaArray = myFormula1 step.
To confirm, the formula by itself works (pasted further below) when entered into cells manually.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(INDEX(MLB," & "X_X_X)"
myFormula2 = "transactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),," & "Y_Y_Y)"
myFormula3 = "5)=$A2,""DNP/SUS/MIN"",""with "" & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions," & "Z_Z_Z)"
myFormula4 = "!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK""))"
Sheets("Sheet1").Select
With Range("E2:AZ140").SpecialCells(4)
.FormulaArray = myFormula1
.Replace ",X_X_X)", myFormula2
.Replace ",Y_Y_Y)", myFormula3
.Replace ",Z_Z_Z)", myFormula4
End With
End Sub
Question update. Using With Range("E2:AZ140").SpecialCells(xlCellTypeBlanks) instead of With Range("E2:AZ140").SpecialCells(4) also ends with the same error.
Here is the full formula being used
=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,"<="&$C2)>0,IF(INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)=$A2,"DNP/SUS/MIN","with " & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,"DNP/SUS/MIN","LEAVE BLANK"))
Testing with a simplified code (example below) led to the realization as YowE3K points out that myFormula1 needs to be valid in order for the procedure to work.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
myFormula1 = "=1+1" & "+2+2"
myFormula2 = "+1+1"
Sheets("Sheet1").Select
With Range("h14:h16").SpecialCells(xlCellTypeBlanks)
MsgBox .Address
.FormulaArray = myFormula1
.Replace "+2+2)", myFormula2
End With
End Sub

When you set a formula using FormulaArray = ..., it needs to be a valid formula. (I think after each Replace the formula needs to continue being valid too, but I haven't tested that. Edit: No, if the Replace would create an invalid formula, it just doesn't process it - but it doesn't crash.)
Your problems all seem to stem from the use of invalid formulas in your myFormula1 variable.
I suggest you use the following:
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(1232=$A2,""DNP/SUS/MIN"",""with ""&1233),1234)"
myFormula2 = "INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)"
myFormula3 = "INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)"
myFormula4 = "IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK"")"
'Insert the formula
With Sheets("Sheet1").Range("E2:AZ140").SpecialCells(xlCellTypeBlanks)
.FormulaArray = myFormula1
.Replace "1232", myFormula2
.Replace "1233", myFormula3
.Replace "1234", myFormula4
End With
End Sub

Setting .FormulaArray to a range of cells in VBA is the same as pressing CTRL+SHIFT+ENTER while the entire range is selected. This is used when a single formula is returning an array of results and you want to display that array in the range of selected cells. This requires a contiguous range of cells to display the array. Trying to set .FormulaArray on a non-contiguous range of cells will fail, regardless of whether the formula is good or not.
I think you're trying to create an Array Formula that returns a single result after performing analysis on arrays; and you want this formula used in all blank cells.
In Excel, you would need to array-enter the formula into a single cell and then copy the formula into other cells.
Similarly, you need to do it in 2 steps in VBA. You need to first set the .FormulaArray for just one cell. This will also confirm that the formula is being constructed correctly in VBA. You can then copy that cell to all blank cells, using PasteSpecial if you only want to copy the formula.
Alternatively, you could loop through all blank cells setting the .FormulaArray individually, e.g.:
Dim raCell As Range
For Each raCell In Range("E2:AZ140")
If IsEmpty(raCell) Then raCell.FormulaArray = ...
Next
However, as you have dynamic references, you would need to construct the FormulaArray carefully to correctly determine the formula required based on the .Row and .Column of the current raCell.
Copy and paste would be safer if you have an "achor" point. Somewhere you know you can always enter the exact same formula and get the correct result when copied and pasted to all other cells.

Related

vlookup with dynamic lookup_value using VBA?

I'm new to using the dynamic lookup value, I tried following the piece of advice from How to perform an excel vlookup with dynamic lookup_value using VBA? to fetch a value dynamically from another workbook.
This below code throws #Name? error.
Request your help to resolve the error.
Code Excerpt:
Dim ws As Worksheet
Dim dynamic_lookup_value As Range
Dim LocationRef As Range
Set ws = ActiveWorkbook.Worksheets("XYZ")
Set dynamic_lookup_value = ws.Cells(2, 1)
ActiveWorkbook.Names.Add Name:="dynamic_lookup_value", RefersTo:=Worksheets("XYZ").Cells(2, 1)
Set LocationRef = ws.Cells(2, ActiveColumn)
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(" & dynamic_lookup_value.Address(0, 0) & ",'[ABC.xlsx]XYZ'!C1:C26,MATCH(""Location Description"",'[ABC.xlsx]XYZ'!R1C1:R1C26,0),)," & LocationRef.Address(0, 0) & ")"
After execution, the formula appears as
=IFERROR(VLOOKUP('A2','[HC report.xlsx]HC Report'!$A:$Z,MATCH("Location Description",'[HC report.xlsx]HC Report'!$A$1:$Z$1,0),),'G2')
Please note lookup value appears 'A2'(with single codes). Tried to declare the dynamic_lookup_value using the following piece of code but in vain.
ActiveWorkbook.Names.Add Name:="dynamic_lookup_value", RefersTo:=Worksheets("XYZ").Cells(2, 1)
If I manually remove the Singe code before and after the A2 and G2, then the formula works fine.
Request the experts advise to resolve this issue.
Many thanks,
Prabhu
New Answer:
Having been able to replicate you error, I think I have a solution: Replace your ActiveCell.FormulaR1C1 with ActiveCell.Formula. This solved it in my simple re-creation of the problem (using the immediate-window)
This works (sets a reference to cell A1 in cell A2, based on address of Cell A1:
Cells(2,2).Formula = "="&Cells(1,1).Address(0,0)
While this doesn't work (gives same issue with 'A1' in single quotes as you had): Cells(2,2).FormulaR1C1 = "="&Cells(1,1).Address(0,0)
I think there may be some confusion between named ranges and range variables in VBA. However, one problem in your formula is an inconsistent application or RC notation so you need
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(" & dynamic_lookup_value.Address(0, 0, xlR1C1) & ",XYZ!C1:C26,MATCH(""Location Description"",XYZ!R1C1:R1C26,0),)," & LocationRef.Address(0, 0, xlR1C1) & ")"

How to add a Formula To Cell using VBA [duplicate]

This question already has answers here:
How do I put double quotes in a string in vba?
(5 answers)
Closed 1 year ago.
I am attempting to write some VBA which will add header text to 3 cells then fill a formula all the way down to the last row. I have written the below, which writes the headers no problems, but when it get's to my first .Formula it throws a
Application Defined or Object Defined error
What needs to be altered so that this macro will execute successfully? (The formulas were pulled directly from the formula in the cell, so I know they are valid formulas at least on the "front-end")
Function Gre()
Range("E2").Select
ActiveCell.FormulaR1C1 = "Under"
Range("F2").Select
ActiveCell.FormulaR1C1 = "Over"
Range("G2").Select
ActiveCell.FormulaR1C1 = "Result"
With Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(C2<B2,B2-C2,"")"
End With
With Range("F2:F" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(C2>B2,C2-B2,0)"
End With
With Range("G2:G" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(F2>0,'Issue',"")"
End With
End Function
The problem is likely that you are escaping the quotes with the formula.
What you need is:
.Formula = "=IF(C2>B2,B2-C2,"""")"
for the first one, for example. The other quotes need to be doubled as well.
As a side-note, it would also be best to specify the sheet you are working on with something like:
Dim ws as worksheet
Set ws = Sheets("mySheet")
ws.Range("E2").FormulaR1C1 = "Under"
etc.
If you don't do this, you can sometimes have errors happen while running the code.
As suggested by OpiesDad, to minimize ambiguity, avoid ActiveCell and the like.
Using Select will also slow down performance a lot compared to assigning to cells directly.
I'm pretty sure you need to escape quotes in Excel formulas inside of VBA by doubling the quotes, so a normal empty string becomes """". You also have Issue in single quotes in a formula, which I'm pretty sure will error in Excel; that should be in escaped double quotes as well.
I'm having a hard time figuring out what Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row) actually does, but it sounds like you want to select E2 to the last used row of the sheet. Avoid Rows.Count or just generally referring to the rows of a sheet, as that will go to row 10^31. Use Worksheet.UsedRange to get the range from the first row and column with content to the last row and column with content. This also includes empty strings and can be a bit tricky sometimes, but is usually better than dealing with thousands of extra rows.
Also,
You don't need to use With if your only enclosing one statement, although it won't cause any problems.
I would not mix use of Range.Formula and Range.FormulaR1C1 unless you have a reason to.
Function Gre()
Dim ws as Worksheet
Set ws = ActiveSheet
Dim used as Range
Set used = ws.UsedRange
Dim lastRow as Integer
lastRow = used.Row + used.Rows.Count - 1
ws.Range("E2").Formula = "Under"
ws.Range("F2").Formula = "Over"
ws.Range("G2").Formula = "Result"
ws.Range("E2:E" & lastRow).Formula = "IF(C2<B2, C2-B2, """")"
ws.Range("F2:F" & lastRow).Formula = "IF(C2<B2, C2-B2, 0)"
ws.Range("G2:G" & lastRow).Formula = "IF(F2>0, ""Issue"", """")"
End Function
The first issue is the selecting of cells. This requires the macro to select the cell, then determine the cell address. If you need to actually select a cell, use Application.ScreenUpdating = False. Then the macro doesn't have to show the cursor selection of a cell. Dropping the select and incorporating the range into the formula assignment code line like below will gain some speed/efficiency.
Range("E2").FormulaR1C1 = "Under"
Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row) is the code version of selecting the last cell in a blank column (row 1048576), then using the keystroke of ctrl and the up key to determine the lowest/last used cell. This gets you a row count of 1 every time since the column is blank. Since you're looking for the last row. It may be faster to count down from the top. My favorite method for this is a loop. Increment a variable within a loop, while looking for the last row. Then, the variable can be used instead of your bottom up strategy.
t = 0
Do Until Range("C2").Offset(t, 0).Value = ""
t = t + 1
Loop
With Range("E2:E" & t)
.Formula = "=IF(C2<B2,B2-C2,"""")"
End With`
Just like TSQL, quote characters need their own quote characters.
.Formula = "=IF(C2<B2,B2-C2,"""")"
The Range Fillup VBA function can be utilized in this case to fill all cells from the bottom with a common formula, accounting for Excel Formula Reference Relativity. The code below starts with the range that we got from the loop counter. Next, we set a variable equal to the total rows in Excel minus the row corresponding to the counter row. Then, we resize the original region by the necessary rows and use the FillDown function to copy the first formula down.
Here's the resulting code. This will fill the range starting from the last row in Excel.
Sub Gre()
Range("E2").FormulaR1C1 = "Under"
Range("F2").FormulaR1C1 = "Over"
Range("G2").FormulaR1C1 = "Result"
Do While Range("e2").Offset(t, 0).Value <> ""
t = t + 1
Loop
Range("E2").Offset(t, 0).Formula = "=IF(C2<B2,B2-C2,"""")"
r1 = Range("e2").EntireColumn.Rows.Count
r2 = Range("E2").Offset(t, 0).Row
Range("E2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
Range("F2").Offset(t, 0).Formula = "=IF(C2>B2,C2-B2,0)"
Range("F2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
Range("G2").Offset(t, 0).Formula = "=IF(F2>0,""Issue"","""")"
Range("G2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
End Sub
As well as using double quotes you may need to use 0 in the first two formula otherwise they may evaluate to empty strings. This may give unexpected results for the last formula i.e. incorrectly return "Issue".
If you do not have blank columns between your data and the 3 new columns you can use CurrentRegion to determine the number of rows:
Range("E2:E" & Cells.CurrentRegion.Rows.Count).Formula = "=if(C2'<'B2,B2-C2,0)"
Range("F2:F" & Cells.CurrentRegion.Rows.Count).Formula = "=if(C2>B2,C2-B2,0)"
Range("G2:G" & Cells.CurrentRegion.Rows.Count).Formula = if(F2>0,""Issue"","""")"
Please try the following sample hope it will help you to wright formula in VBA
Sub NewEntry()
Dim last_row As Integer
Dim sht1 As Worksheet
Dim StockName As String
Set sht1 = Worksheets("FNO MW")
last_row = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'MsgBox last_row
StockName = sht1.Cells(last_row, 1).Value
sht1.Cells(last_row, 1).Formula = "=RTD(""pi.rtdserver"", ,"" " & StockName & " "", ""TradingSymbol"")"
End Sub

Setting variables VBA

complete novice here
I started some VBA a few days ago, I have simple question but cant seem to find what I am doing wrong.
I am trying to make a button which will take the coordinates of the active cell and compare them to another worksheet to retrieve a specific value from another table.
I set variables to the active cell column and row, I want to do this so I can later compare these locations to another worksheet and get the value at a specified position on another worksheet.
So far I have written simply what I could find on the internet as I have no formal training.
The msgbox at the end is just to test whether or not it actually picks up the reference.
Sub CommandButton1_Click()
Dim Arow As Range
Dim Acol As Range
Set Arow = Worksheets("Sheet1").Range(ActiveCell.Row)
Set Acol = Worksheets("Sheet1").Range(ActiveCell.Column)
MsgBox (Arow)
End Sub
So far I have error run-time error '1004' Application defined or object defined error highlighting the 4th Row. If anyone could help me solve this or redirect me to some help it would be much appreciated.
I think this won't work, you should put there
Set arow = Worksheets("Sheet1").Range(ActiveCell.Row & ":" & ActiveCell.Row)
Putting there simply number won't work. For the column, you should put there somethong like C:C. For getting letter of column, see this qestion: Function to convert column number to letter?
For more information about Range property, please see official documentation https://msdn.microsoft.com/en-us/library/office/ff836512.aspx.
The thing is, that you have to supply either the address in so called A1 reference, which is "A1", or "$A$1" or name of cell, etc, or you have to supply two Range objects, such as two cells Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1,1), Worksheets("Sheet1").Cells(2,2)), which defines area starting with upper-left corner in first parameter and lower right in second parameter.
ActiveCell.Row and ActiveCell.Column returns you some Integer value representing number of row and column, i.e. if you point cell B4, ActiveCell.Row would return 4, and ActiveCell.Column gonna return 2. An Range() property need as an argument whole adress for some range, i.e. Range("C6") or Range("G3:J8").
When you have your column as a number, you can use Cells() property for pointing first and last cell in your range, i.e. Range(Cells(2, 4), Cells(6, 8) would be the same range as Range("D2:H6").
Following this, one of the ways that you can do what you have described is:
Sub CommandButton1_Click()
Dim Rng As Range
Set Rng = Worksheets("Sheet1").Cells(ActiveCell.Row, ActiveCell.Column)
End Sub
Now you have under variable Rng an Range of the same coordinates as ActiveCell, but in Sheet1. You can pass some value into i.e Rng.Value = "Hello World", paste something with Rng.PasteSpecial xlPasteAll etc.
if you want the value from other sheet at the same location as activeCell, use this code,
Private Sub CommandButton1_Click()
valueFromOtherSheet = Sheets("Sheet2").Range(ActiveCell.Address)
MsgBox (valueFromOtherSheet)
End Sub
Like the others have said, it's just about knowing your variable types. This is another way you could achieve what you want
Sub CommandButton1_Click()
Dim Acell As Range
Set Acell = Worksheets("Sheet2").Range(ActiveCell.Address)
MsgBox "Value on ActiveSheet: " & ActiveCell.Value & vbNewLine & _
"Value on Sheet2: " & Acell.Value
End Sub
Thank you everyone for the help and clarification, In the end I was able to come up with some code that seems to do what I need it to.
Private Sub CommandButton1_Click()
Dim cabDate As Range
Dim searchCol As Integer
Dim newindex As Range
Set cabDate = WorksheetFunction.Index(Range("A1:O9999"), ActiveCell.Row, 2)
searchCol = ActiveCell.Column
Set newindex = WorksheetFunction.Index(Worksheets("Deadlines").Range("A1:O9999"), cabDate.Row, searchCol)
MsgBox (newindex)
End Sub
I wasn't aware about conflicting data types so thank you all for the assistance.

Preserve null strings when assigning to .Value with VBA

(edit: added 2 more restrictions to solutions)
I have a table (listobject wise) in which I need to duplicate certain rows. I'm using SourceListRow.Range.Value2 = DestListRow.Range.Value2 for efficiency reasons (copying whole ranges in one go). All formula columns after the copied cell ranges auto-expand perfectly into the new rows and act upon the copied data. I'm using Excel 2010 here on Windows.
However, although I've already been using this sort of code for eons, I've only now stumbled upon an oddity when using Range.Value / Range.Value2: if you assign an empty string to it, the final cell value will not be an empty string, but it will be Empty. That is: the data isn't copied over faithfully, and the copy can differ from the source, especially if consecutive formulas use ISBLANK etc. on it. Therefore the same formula will have different results when working on the copy vs. the source.
See below test code. Open a new, blank, Excel workbook, go to VBA, add a new module and add the following code:
Sub Test()
ActiveSheet.Range("a1").Formula = "="""""
ActiveSheet.Range("b1").Formula = "=isblank(a1)"
ActiveSheet.Range("c1").Value2 = TypeName(ActiveSheet.Range("a1").Value2)
ActiveSheet.Range("a2").Value2 = ActiveSheet.Range("a1").Value2
ActiveSheet.Range("b2").Formula = "=isblank(a2)"
ActiveSheet.Range("c2").Value2 = TypeName(ActiveSheet.Range("a2").Value2)
ActiveSheet.Range("a3").Value2 = ""
ActiveSheet.Range("b3").Formula = "=isblank(a3)"
ActiveSheet.Range("c3").Value2 = TypeName(ActiveSheet.Range("a3").Value2)
ActiveSheet.Range("a4").Formula = ActiveSheet.Range("a1").Formula
ActiveSheet.Range("b4").Formula = "=isblank(a4)"
ActiveSheet.Range("c4").Value2 = TypeName(ActiveSheet.Range("a4").Value2)
Call ActiveSheet.Range("a1").Copy
Call ActiveSheet.Range("a5").PasteSpecial(xlPasteValues)
ActiveSheet.Range("b5").Formula = "=isblank(a5)"
ActiveSheet.Range("c5").Value2 = TypeName(ActiveSheet.Range("a5").Value2)
End Sub
Then run it and look at the sheet;
B1 tells FALSE (as it should - the cell is not empty), and C1 tells "String" (the cell value is indeed an empty string);
B2 tells TRUE, even though we just copied over A1's value as-is; C2 tells "Empty", while it should tell "String" if the value was copied over faithfully;
as a test, B3 tells TRUE, even though we just set it explicitly to an empty string; C3 again tells "Empty" to confirm the data mangling;
assigning Range.Formula to OtherRange.Formula works (the String data type is preserved in B4), but I do not want to copy formula's, I want to copy only the values!
as a test I mimic what the GUI would yield in A5, and sure enough, Copy/Paste-As-Values does preserve the is-an-empty-string state...
What to do?
using Range.Copy / Range.PasteSpecial(xlPasteValues) is unacceptable, performance-wise and clipboard-wise;
using .Formula is also not an option, because I want to copy the values;
I could iterate over all values in the array, testing if they're a null string and then setting those cell's formula to ="", but I want to copy whole multi-cell ranges in one go to gain efficiency here...
I can't use autofilters and such because my data lives in a table (a.k.a. ListObject); I could use the table's own autofilter, but people may have it in use already so I'd have to restore it afterwards which is too much of a kludge.
using Range.Find and Range.Replace is not an option either, since that changes the user's Find/Replace dialog settings.
All ideas appreciated!
SpecialCells(xlCellTypeBlank) and AutoFilter treat null strings differently. Is your source data filterable? If so, could you use a placeholder value and then change the cells to have .Formula = "=""""" after copying?
I took your sample code and generated the workbook, then added a row above it for a filter header. The below code would change all null strings to "ChangeMe"; you could then copy over the values and replace all instances of "ChangeMe" in your destination with "=""""" using Range.Replace.
Sub Test2()
ActiveSheet.Range("A2:A6").SpecialCells(xlCellTypeBlanks).Interior.Color = 255 'Just to prove that xlCellTypeBlanks only selects actual blanks
ActiveSheet.Range("A1:A6").AutoFilter Field:=1, Criteria1:="=" 'Shows both actual blanks and ZLS/null strings
ActiveSheet.Range("A1:A6").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True 'Be able to use SpecialCells(xlCellTypeVisible) to reference all ZLS
ActiveSheet.Range("A2:A6").SpecialCells(xlCellTypeVisible).Value2 = "ChangeMe"
'Now unfilter and unhide your data, copy using .Value2, then .Replace "ChangeMe" with "="""""
End Sub
I think that accomplishes what you are trying to do - let me know if this is the right direction for a solution.
Edit: misinterpreted original question. Below old answer is incorrect.
While not quite as efficient as your original code, using .AutoFilter is much more efficient than looping through many cells. Furthermore, .AutoFilter treats zero-length strings and empty cells the same.
Something like this:
Sub CopyAndClearFakeBlanks()
Dim WSSource As Worksheet
Dim WSDest As Worksheet
Dim LRow As Long
Dim LPasteRow As Long
Set WSSource = Sheets("Source Data")
Set WSDest = Sheets("Paste Here")
LRow = WSSource.Range("A:A").Find(what:="*", searchdirection:=xlPrevious).Row 'Note that this will ignore blanks, so you may want to use a different method for finding your last row. Depends on how your users would need the data if there are trailing blanks.
On Error Resume Next
LPasteRow = 2 'Always need at least one row before the data for filtering properly; you can delete after if necessary
LPasteRow = WSDest.Range("A:A").Find(what:="*", searchdirection:=xlPrevious).Row + 1
WSDest.AutoFilterMode = False
On Error GoTo 0 'ofc use proper error handling in your actual code
WSDest.Range("A" & LPasteRow & ":A" & LPasteRow + LRow - 1).Value2 = WSSource.Range("A1:A" & LRow).Value2
WSDest.Range("A" & LPasteRow - 1 & ":A" & LPasteRow + LRow).AutoFilter field:=1, Criteria1:="=" 'Show blank or ZLS only
On Error Resume Next
WSDest.Range("A" & LPasteRow & ":A" & LPasteRow + LRow).SpecialCells(xlCellTypeVisible).Clear 'Turn them into true blanks
WSDest.ShowAllData
WSDest.AutoFilterMode = False
On Error GoTo 0
Set WSDest = Nothing
Set WSSource = Nothing
End Sub

macro: if radio button on then copy formula down a range

My prob is this:
I want to be able to use a macro to copy & calculate formula down a range of cells if radio button is on.
But I don't know how to set the variable inside the formula. The macro below should copy the formula to ranges shown (I12:I252, K12:K252, M12:M252).
The formula itself includes a subtraction of two cells in the range of C12:C252 & B12:B252. I cannot seem to reference those cells. I thinks that's the problem...
Anyway, it doesn't work. Any help would be greatly appreciated.
Thanks!
Dim shp1 As Shape
Dim shp2 As Shape
Dim i As Long
On Error Resume Next
Set shp1 = Worksheets("Worksheet").Shapes("Button 1")
Set shp2 = Worksheets("Worksheet").Shapes("Button 2")
If shp1.ControlFormat.Value = xlOn Then
MsgBox "Auto Calculating"
For i = 12 To 252
Range("I" & i).Formula = "=IFERROR(((C & i)-(B & i))*I6/(E7-E6);"")"
Range("K" & i).Formula = "=IFERROR(((C & i)-(B & i))*J6/(E7-E6);"")"
Range("M" & i).Formula = "=IFERROR(((C & i)-(B & i))*K6/(E7-E6);"")"
Next i
Else
If shp2.ControlFormat.Value = xlOn Then
MsgBox "Manually insert calculation"
End If
End If
Few improvements:
Replace the ; in your formulas with ,. ; is your local
setting, but .Formula uses the English setting!
If you want to refer to each column, you need place the i outside the quoatation marks, i.e. instead of =IFERROR(((C & i)... write =IFERROR(((C" & i & ")...
No need to loop each cell and set the formula. If you use $ in your formula properly, you can replace all with one formula: =IFERROR(($C12-$B12)*I$6/($E$7-$E$6),"")
Better use .FormulaR1C1 - this way, your formula will also work, when you would applied it to some other range. To easily convert a formula, type it normally into a cell and the run ? Selection.FormulaR1C1in the VBA Immediate Window. The above formula translates to =IFERROR((RC3-RC2)*R6C/(R7C5-R6C5),"")
Don't hard code cell references (in your case I12:K252). Better assign this range to a named range and use this as a reference. This way, your code will also work if you later add/remove rows or columns.
Don't use On Error Resume Next! This is a invitation to oversee an error that should be fixed
Optional: Alternatively to accessing the controls directly in VBA, you can also assign each one to a cell, name this cell as in step 4 and refer to in by this name. Makes your code more flexible/less complex!
So all in all, I end up with:
Public Sub YourSub()
If Range("SwitchOne") Then
Range("YourRange").FormulaR1C1 = _
"=IFERROR((RC3-RC2)*R6C/(R7C5-R6C5),"""")"
Else
If Range("SwitchTwo") Then
MsgBox "Manually insert calculation"
End If
End If
End Sub