Directly copying values of evaluated Excel functions - vba

I know that I can copy a column containing evaluated formulas, paste it into an adjacent column, and specify to paste values (i.e., a text string), so that the value sticks and I can then select, copy, and edit the value text as I desire. However, I would like a more direct way to produce an editable column of values.
In order of preference, I would be satisfied if I could either:
(1) simply copy the values directly from the formula-containing cells by specifying a copy mode/option instead of having to specify a paste mode/option (so that if I want to paste the values outside Excel, for example, I can do so directly) - I believe this is not possible but would like to know if I have overlooked something
(2) write the formulas in a way that "throws" the evaulated values to other cells, overwriting whatever is in those other cells as needed, but passing no trace of the formula itself to the other cells
(3) use a worksheet macro that runs in the background and automatically copies values from column A into column B whenever column A values are updated or
(4) perform some operation on the formula column that removes the formulas but leaves the (editable) values (with the obvious drawback that you can't reuse the formulas once they are gone).
Which of these are possible?

The following Event Macro:
Private Sub Worksheet_Calculate()
Dim r As Range
Application.EnableEvents = False
For Each r In Columns(1).SpecialCells(xlFormulas).Cells
r.Offset(0, 1).Value = r.Value
Next r
Application.EnableEvents = True
End Sub
will monitor calculations in column A. Whenever a calculation is made, all the values of the formulas in column A will be copied to column B
Note:
the data will not be copied
macros must be enabled
all the formula results will be copied, even un-changed results

Related

SpecialCells in Excel to return value of a formula

I wanted a quick simple way to copy cell values to another sheet using SpecialCells in Excel as opposed to looping
My VBA code is as below:
Sub copyMissingData()
Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeConstants).Copy Worksheets("Destination").Range("missing_qbc")
End Sub
My source data Z4:Z20000 has formulas that returns a value (texts/numbers/fraction etc) or blank "". I want the copy to ignore the blanks, but copy any other value returned
The VBA code above using SpecialCells(xlCellTypeConstants) doesn't work because of the formula in the source range.
My question: Is there a straightforward way I can use range.specialcells to copy my data from a worksheet to another bearing in mind that source cells contain formulas and the formulas may produce empty string cells which will need to be skipped
If you have formulas, why are you trying to select the constants?
Use this:
Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeFormulas, 23).Copy
Worksheets("Destination").Range("missing_qbc").pastespecial(xlPasteValues)
The 23 means "Numbers, Texts, Logicals and Errors".
Doing the copy and paste separately ensure blanks are skipped (if that's what you mean by "ignore").
Paste values makes sure only the values get pasted, not the formulas themselves.
Please note that if you have a formula in a cell, it is not blank. Even if the formula produces an empty string value as a result, the cell itself is not empty! In htat case, you need to do a copy-paste values in place before you do anything else - and even then Excel sometimes doesn't consider blank cells blank. If this is the case, you need to iterate (loop) through the cells, and copy them one-by-one.
The easiest way I can think of is to remove the blanks after copying all:
Set rngFrom = [Source!Z4:Z2000]
Set rngTo = [Destination!missing_qbc].Resize(rngFrom.Rows.Count, 1)
rngTo.Value = rngFrom.Value
rngTo.SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
The more complicated way is with array formula, but doesn't need VBA.

Copy variable range on one sheet to next empty row on another sheet

I need to copy all data in columns P:Y and paste it into the next blank cell in column A.
I've written the code below, which works fine, except that the data it is copying (P:Y) contains a formula down the whole column and although I am pasting values in order to only get the value returned, it is counting all cells as containing data.
By this I mean that when I run the macro the first time, it works. But when I run it a second time, (which I need to do) when it finds the last empty row. It isn't the last empty row! It selects a row far below the actual last row that I can see data in.
There is no data in the empty rows and no formula in them, but for some reason that is beyond me, it is treating the rows as not empty.
The data returned in columns P:Y by the formula will change every month, so I can't define a specific range.
How can I modify the code to rectify this - or is there a better way I could do this?
Sub SelectRangea()
Sheets("Set Up Data").Select
Range("P2:Y10000").Select
Application.CutCopyMode = False
Selection.Copy
With Sheets("Pasted Report")
lst = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A" & lst).PasteSpecial xlPasteColumnWidths
.Range("A" & lst).PasteSpecial xlPasteValues
End With
End Sub
When a cell contains a formula, it will have a value, even though it seems empty when inspecting the cell on the sheet. So if you copy such seemingly empty cells and paste them somewhere else (even if only as values), the pasted-to cells now do contains something (i.e. they're not really empty anymore; they're an empty string to be exact instead of VBA's Empty).
Range.End will then move to those last empty cells instead of moving to the last true filled cell.
You can see this for yourself if you do this by hand on an empty sheet: enter in A1:A5 the formula ="", then copy the range as values to B1:B5, then select B10 and press Ctrl-Up.
A fix would be to use the Range.End method, and then just inspect the cell contents going upwards. Or use Range.Find, but keep in mind that that also alters the settings in the user's Find dialog.

VBA Hide Row in table if Specified Column is Empty

I am trying to add to a macro I have that will hide every row that has no text in a column named Authorization. Please see the code I have below, I thought this may be on the right track but it does not hide any rows.
Cells.EntireRow.Hidden = False
For Each cell In Range("Authorization").End(xlUp)
If cell = "" And cell.Offset(1, 0) = "" Then cell.EntireRow.Hidden = True
Next cell
Edited to add how to define a dynamic named range
It is the fact that you have set the whole column to the name "Authorisation" that I think makes your code freeze, because the whole column is 1 million rows (if you have 2007 or above), and the code will still check even blank rows, so its doing it 1 million times. 1 Option is to rather than set it to the whole column, you could use a "Dynamic Named Range" which will expand and grow as data is added. There are several different formulas to do this, but based on the fact your data may contain blanks, this version of the formula will expand down to the last populated row in the column. My example uses colum A as you havent specified what column you are using, so change A to suit your needs.
You need to open the Names manager, from the Formulas tab
From the dialog box, find your "Authorisation" name.
Select it and you should see its current formula at the bottom of the dialog box, replace that with the following formula:
=OFFSET(Sheet1!$A$3,0,0,MATCH("*",Sheet1!$A:$A,-1)-2,1)
In the above formula:
Sheet1 is my sheet, replace it with yours a needed
$A$3 is the starting row of the name, so based on your comments, have set this as column A row 3
0,0, Are defaults you should not need to change
$A$A$ is the column it is counting values, so change as required
-1 is a default, leave as is
-2 is subtracting 2 from the count because we are starting on row 3, so if you change the starting row, change this
the last 1, defined how many columns your named range covers, in your example it is just 1, so this should not need changing.
Once you have defined the name in this way, the code below should work a lot quicker as it will only loop through down to the last row of entered data. There is one possible issue I can see with this and that is if the very last cell in column A is blank, but the rest of the row isn't, this will miss out the last row. I could fix this by using a different column to count what constitutes the last row, but need to know whicj column would always have a value in it.
< Original answer and code>
not sure you code matches the description of what you want it to do, namely you seem to be trying to check the row beneath the current cell as well, is this what you really wanted? Anyhow your syntax is slightly wrong. I have written and tested this and it works, I have swapped your offset around so my code is checking the cell in the named range "Authorisation" and then also checking the cell to the right. Amend to suit your needs
Sub test()
Dim c As Range
For Each c In Range("Authorisation").Cells
If c.Value = "" And c.Offset(0, 1).Value = "" Then c.EntireRow.Hidden = True
Next c
End Sub

Keeping column formulas in a table header

Is it possible to have the formulas that I need applied on columns be saved or applied to a column header or some kind of metadata so that as and when I add new rows to my Excel table the Formulas get applied to the columns?
Scenarion:
I am creating a template Table, which will have no rows at first.
On a separate sheet (or same sheet for that matter) once the user selects the number of rows to be generated in the table, I dynamically add rows to the table using VBA.
The idea is I may not have any rows in the table at beginning OR user may have deleted rows manually.
When I programmatically add new rows, I want the Formulas applied on the cells as well. Most of the formulas I am using are either of the three types:
Structured table reference, Excel functions like SUM, AVERAGE etc and custom function names.
Updated:
Here is what I have tried:
1> tried applying the formula to the header itself.
Result: The header it self changes with #REF! error. I think the behavior is correct. So it's a no-go option.
2> Tried creating one row and apply the formula to the row. That works, but the problem is, I do not want a dummy row to begin with.
3> Using VBA code to add row to the table using
ActiveWorkbook.Worksheets("Sheet3").ListObjects("Table2").ListRows.Add AlwaysInsert:=True
inside a for loop.
The new rows retain the visual style sheets, but does not seem to retain the formulas. Just blank cells.
Could the fomrmulas be in header cell commnets?
And then with VBA add the formula for the current row:
Sub test()
Dim headerCells As Range
Set headerCells = Range("B2:E2")
OnNewRow 3, headerCells
End Sub
Sub OnNewRow(newRow As Integer, headerCells As Range)
Dim headerCell As Range, targetCell As Range, formulaFromComment As String
For Each headerCell In headerCells
formulaFromComment = GetFormulaFromComment(headerCell)
If (formulaFromComment = "") Then _
GoTo NextHeaderCell
Set targetCell = Intersect(headerCells.Worksheet.Rows(newRow), _
headerCell.EntireColumn)
AddFormula newRow, targetCell, formulaFromComment
NextHeaderCell:
Next
End Sub
Sub AddFormula( _
newRow As Integer, _
targetCell As Range, _
formula As String)
formula = Replace(formula, "{ROW}", newRow)
targetCell.formula = formula
End Sub
Function GetFormulaFromComment(headerCells As Range) As String
' TODO
GetFormulaFromComment = "=SUM($C${ROW}:$E${ROW})"
End Function
Just use tables.
If you highlight cells and choose Insert Table from the ribbon, it doesn't just give you formatting and filters. It also, if you build them the right way, stores column formulas once per column instead of once per cell. Also, the formulas are more readable!
For formulas, you can't use cell addresses if you want it to be a single column formula unless they are absolute. (E.g. $A$1, not A1.) Instead, you use [ColumnTitle] for the entire column (where "ColumnTitle" is the actual title of that column) and [#ColumnTitle] for the column value in the same row. So if "Cost" was the title of column B, "RunningTotal" was the title of column C and your formula for C6 was therefore =B6+C5, you'd instead use a formula of =[#Cost]+OFFSET([#RunningTotal],-1,0)] which is longer but much easier to read/maintain/debug, and if you change a column title then the formulas change too! No VBA required. Given this, plus being able change columns for the entire columns at once, plus being able to refer to other columns in other tables without worrying about cell addresses (e.g. MAX(Table1[Cost])), plus being able to style the tables so easily, plus the integration with Power-Query, and VBA support. (See learn.microsoft.com.) Whether VBA or otherwise, add a row to your table and the columns with a single column formulas will automatically carry over into the new row.
Not sure about Table templates or VBA but perhaps there is another option by using =ARRAYFORMULA()
For example, say you had a header row and 3 columns and wanted your last column to be the product of the first two. In cell C2 you could enter the following:
=ARRAYFORMULA(A2:A*B2:B)
This has three benefits:
Skips the first row completely
Effectively applies the formula to every row which is useful if you later decide to insert a row (your question)
Only one location to modify the formula for every single row
Although, it may not be immediately obvious where how/where the cells are being calculated. (hint: ctrl+~ may help)

Excel VBA - Interpret "N/A" Values

I am traversing a spreadsheet which contains a column of prices, in the form of double types. I am trying to locate a missing value which is shown on the spreadsheet as "n/a", but it is not letting me interpret this as a string type.
The cell containing "n/a" seems to be an integer type; how can I read this?
If all you want to do is to check for the error value then:
Application.WorksheetFunction.IsNA(rngToCheck.Value)
where rngToCheck is the cell which you want to check for the #N/A error value
(There's a list of the worksheet functions which can be called from Excel VBA here)
You could also examine rngToCheck.Text as this will contain the string "#N/A"
If instead, you want to read the formula in the cell which generated the #N/A then rngToCheck.Formula would do that
A cell containing #N/A is retrieved by VBA as a variant containing an error code
In general its usually best to assign Excel cells to Variants because a cell can contain a number(double), logical, string or error and you cannot tell in advance what the cell wil contain.
You can prepare the spreadsheet you like to check as described below and evaluate the special cells containing the IS Functions, it is easy to check them for True or False in VBA. Alternatively, you can write your own VBA function as shown below.
There are Excel functions which check cells for special values, for example:
=ISNA(C1)
(assumed that C1 is the cell to check). This will return True if the cell is #N/A, otherwise False.
If you want to show whether a range of cells (say "C1:C17") has any cell containing #N/A or not, it might look sensible to use:
=if(ISNA(C1:C17); "There are #N/A's in one of the cells"; "")
Sadly, this is not the case, it will not work as expected. You can only evaluate a single cell.
However, you can do it indirectly using:
=if(COUNTIF(E1:E17;TRUE)>0; "There are #N/A's in one of the cells"; "")
assuming that each of the cells E1 through E17 contains the ISNA formulas for each cell to check:
=ISNA(C1)
=ISNA(C2)
...
=ISNA(C17)
You can hide column E by right-clicking on the column and selecting Hide in Excel's context menu so the user of your spreadsheet cannot see this column. They can still be accessed and evaluated, even if they are hidden.
In VBA you can pass a range object as RANGE parameter and evaluate the values individually by using a FOR loop:
Public Function checkCells(Rg As Range) As Boolean
Dim result As Boolean
result = False
For Each r In Rg
If Application.WorksheetFunction.IsNA(r) Then
result = True
Exit For
End If
Next
checkCells = result
End Function
This function uses the IsNA() function internally. It must be placed inside a module, and can then be used inside a spreadsheet like:
=checkCells(A1:E5)
It returns True, if any cell is #N/A, otherwise False. You must save the workbook as macro-enabled workbook (extension XLSM), and ensure that macros are not disabled.
Excel provides more functions like the above:
ISERROR(), ISERR(), ISBLANK(), ISEVEN(), ISODD(), ISLOGICAL(),
ISNONTEXT(), ISNUMBER(), ISREF(), ISTEXT(), ISPMT()
For example, ISERR() checks for all cell errors except #N/A and is useful to detect calculation errors.
All of these functions are described in the built in help of Excel (press F1 and then enter "IS Functions" as search text for an explanation). Some of them can be used inside VBA, some can only be used as a cell macro function.