SpecialCells in Excel to return value of a formula - vba

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.

Related

Problems with paste as values in VBA

I have a problem in paste as values a multiple selection, this is what I have to do:
I have a spreadsheet, every cell has a formula in it and I want to create a macro which copy each cell and paste on itself as value (in order to remove every formula). The problem is that there are some cells which are locked, so if I try to copy and paste them excel returns an error and it stops the procedure.
Now I have two possibilities:
case 1: copy and past as values each cell individually, but I have a lot of cells and I have to do this procedure very often.
case 2: create a big selection which contains only the unlocked cells and then copy and paste them all togheter.
case 2 seems to be the better choice, but with excel I can't copy and paste multiple selection...does anyone have a tip for me?
I though to take the big fragmentary selection and copy and paste every block of the selection one by one, but I don't know if is it possible :(
Loop throught every cell in selection and check if they are locked like this:
For Each Z In Selection
if Not Z.Locked Then
'do copy paste here
End If
Next Z

VBA Excel: How to assign range of cells to another range of cells?

New Excel VBA user here. I feel like I made a silly syntax mistake.
I am trying to copy some vertical cells in one worksheet, to horizontal cells in another worksheet.
Worksheets("Master").Range("D14:F14").Value = Worksheets("Temp").Range("B12:B14").Value
However, the above command seems to only paste the value of B12 to cells D14:F14. Is there a way to paste the cells of B12, B13, and B14 to D14:F14?
Use Application.Transpose():
Worksheets("Master").Range("D14:F14").Value = Application.Transpose(Worksheets("Temp").Range("B12:B14").Value)
Or PasteSpecial:
Worksheets("Temp").Range("B12:B14").Copy
Worksheets("Master").Range("D14").PasteSpecial xlPasteAll, , , True
If you only want values then the first is best. When transposing with PasteSpecial one must use the xlPasteAll. It will throw an error if one tries to paste values only with transpose as true.

Directly copying values of evaluated Excel functions

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

Convert Excel Formula to VBA

I have this formula that looks at various criteria across multiple columns and checks to see that if all the all the criteria match, it will paste data from one column to another. I've tried a couple ways to get it into VBA, but I can't seem to get anything to work. Thanks!
=INDEX($D$2:$D$1112,MATCH(1,($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3),0))
You are not going to be able to use that array formula to directly return a value to a cell. VBA does not process an array formula the way that the worksheet can. The best method is to use the worksheet's processing or one of the Application Evaluate methods.
Your lack of a worksheet to reference troubles me. When a formula is in a worksheet cell, it knows what worksheet it is on. When using formulas within VBA, the parent worksheet is a 'best guess' without explicit worksheet referencing.
Here are three methods to put the results from that array formula into Z2:Z4 on the active worksheet. Remember that these cell references should be modified to include the worksheet name.
With ActiveSheet
'this simply puts the formula into the worksheet then reverts the cell from the formula to the returned formula value
.Range("Z2").FormulaArray = "=INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))"
.Range("Z2") = .Range("Z2").Value
'this uses the 'square bracket' method of evaluating a formula on-the-fly
'the formula being evaluated can be array or non-array
'this method is does not like building a formula string from pieces of text
.Range("Z3") = [INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))]
'similar to the method directly above, Application.Evaluate does just that.
'the formula being evaluated can be array or non-array
'this method is easier to build a formula string from pieces of text
.Range("Z4") = Application.Evaluate("INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))")
End With
You need 2 changes:
(1) To use a function in VBA when it is available in native Excel, you need to preface each function with Application.WorksheetFunction. ie:
x = Application.WorksheetFunction.Sum(y,z)
(2) To reference a cell within a sheet, in VBA, you need to access it specifically, in one of a few ways. The simplest for our purposes is the RANGE property, as follows:
x = Application.WorksheetFunction.Sum(Range("A1:A2"))
So to put those two changes together, your formula would look like this:
=Application.WorksheetFunction.INDEX(Range("$D$2:$D$1112",Application.WorksheetFunction.MATCH(1,(RANGE("$A$2:$A$1112"=RANGE("$U$7")*(Range("$C$2:$C$1112"=Range("$W$7")*(Range("$B$2:$B$1112"=Range("F3"),0))
Although I see now having gone through this that you seem to be using an Array Formula - not sure if any special jigging is required to get that to work.

Excel VBA how to select all cells in a dynamic range were the colour index is not 0

I have a SAP Report embedded in a worksheet, it is refreshed via a macro using variables defined in another worksheet. That all works fine, but i am having trouble selecting the data the report generates.
The headings of the report are in and always will fall in this range ("A17:K17"), but the results rows will vary making the total range I want to capture anywhere from ("A17:K18") to (A17:K1000").
The solutions I've already tried didn't work i think because there is almost no consistency in the result data, it's a mixture of text and numbers with empty cells all over the place, in both the rows and columns. Including the occasional completely empty row. This means the methods I have tried before reach a point where it thinks it's reached the end of the populated rows - but it hasn't.
The only factor that remains the same throughout the report is that the cells in the range I want to capture are all filled with a color as default and anything outside the range is unfilled.
To me the simplest solution would be to use VBA to select all the cells beneath and including the headers on ("A17:K17") where the color index is not 0 (blank?) regardless of their contents as I don't mind capturing empty cells. Except I don't know how to do this.
At this point I'd just like to select this range I haven't decided if I'm going to copy it into a new workbook or into an email yet, but that I can do. I've just hit a dead end selecting it.
Quite unsure exactly what it is you require but here's a solution. It's worth noting that both the ColorIndex and Color properties are not necessarily zero with no fill, so if you just change blankCell to a cell with the fill which you define to be blank you'll be good to go.
Sub test()
Set blankCell = Range("A1") ' change this to a cell that you define to be blank
blankIndex = blankCell.Interior.Color
Set cellsDesired = Range("A17:K17")
For Each cell In Range("A17:K1000")
If cell.Interior.Color <> blankIndex Then
Set cellsDesired = Application.Union(cellsDesired, Range(cell.Address))
End If
Next cell
cellsDesired.Select
End Sub