Excel to replace formulas with values - vba

I have an Excel workbook (1) with around 9 sheets that is pulling in and manipulating data from a second workbook (2).
After pulling in the data from workbook (2) I need to be able to replace the formulas in workbook (1) to the resulting values that the formulas have produced, from here I will then save the workbook (1) with the results.
Is there a macro that can do this for me?

On your new workbook some basic code such as:
Sub Value()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
ws.UsedRange.Value = ws.UsedRange.Value
Next
End Sub

While the OP is dated, I want to make note of a non-loop method that is useful. In certain scenarios, loops can really slow down the code execution. To replace formulas in a cell --without a loop-- try:
With Sheets("example").Range("A1:C1000")
.value = .value
End With
You can revise the reference as necessary, but the execution is seamless, fast, and as a bonus - prevents range highlighting that cannot be cleared if you pursued the .copy + .pastespecial xlPasteValues approach.

What seems to work for me is to use concatenate()
So, for example, the formula I have referencing a cell from another sheet is:
=arrayformula(iferror(index('To Be Processed'!X:X,small(if($A$1='To Be
Processed'!$Y2,row('To Be Processed'!X:X)),row((2:2))),"")))
and if I change to the formula to:
=concatenate(arrayformula(iferror(index('To Be
Processed'!X:X,small(if($A$1='To Be Processed'!$Y2,row('To Be
Processed'!X:X)),row((2:2))),""))))
and it puts in the text value from the reference cell into my second sheet.
Which may or may not be helpful depending on how you populate your sheets--I'm not very good with VBA, though, which means I do more things manually :)

Related

Copy values, not formulas, on a worksheet to another

I added a macro to copy a worksheet to another worksheet, so that any changes made after that point can be compared to the original. However, my macro copies over formulas instead of just the values, so when something changes, both sheets change, and the copy serves no purpose. What I have is:
Worksheets("First Sheet").Cells.Copy _
Destination:=Worksheets("Second Sheet").Cells
Is there an easy way to fix this? Thanks!
You need to use Copy >> PasteSpecial and paste only values, this is a 2-line syntax:
Worksheets("First Sheet").Cells.Copy
Worksheets("Second Sheet").Cells.PasteSpecial xlPasteValues
After your macro, you can write this one:
With Worksheets("First Sheet")
Worksheets("Second Sheet").Range(.UsedRange.Address).Cells.Value2 = .UsedRange.Value2
End With
It takes the values of the first sheet and it puts them to the second sheet. The trick with UsedRange is needed, because Worksheets(2).Cells.Value2 = Worksheets(1).Cells.Value2 goes above the usual resources of a normal PC.
This will skip all formula cells in the first sheet:
Sub KopyKat()
Dim r As Range, addy As String
For Each r In Worksheets("First Sheet").Cells.SpecialCells(2)
addy = r.Address
r.Copy Destination:=Worksheets("Second Sheet").Range(addy)
Next r
End Sub

Removing links from copied worksheet

What I want to do
I want a code in my workbook (wbDestination) that opens another workbook (wbBosOriginal) and copies an entire sheet as values (wbBosOriginal has a lot of code in it, in modules and in the worksheet in question, and I do not want this code because it references stuff in wbB that doesn't exist in wbDestination). I have had great problems pasting as values, because it will not paste columns and rows that are currently hidden. So this is why I decided to import the whole sheet instead.
What I tried and what's wrong with it
Here is a block of code I used to copy the worksheet in the destination workbook, in the last index position. The problem with it is that some links still exist to the old workbook (Formulas, validation lists, conditionnal formatting). I have deleted all these links but STILL when I paste the sheet successfully, save and reopen, I have an error saying some content is unreadable. I believe there are still some elements linked to the old workbook.
Set wbBosOriginal = Workbooks.Open(strChosenPath, ReadOnly:=True)
With wbBosOriginal.Sheets("BOS")
.Visible = True
'Pastes the ws in last position in wbDestination
.Copy after:=wbDestination.Sheets(wbDestination.Worksheets.Count)
Set wsNewBos = Worksheets(Worksheets.Count)
'Deletes VBA code in the copied sheet
ThisWorkbook.VBProject.VBComponents.Item(wsNewBos.CodeName).CodeModule.DeleteLines 1, _
ThisWorkbook.VBProject.VBComponents.Item(wsNewBos.CodeName).CodeModule.CountOfLines
End With
The worksheet is successfully pasted with no code in it, with everything else it had previously. I then remove all formulas, conditionnal formatting, and validation lists. Even after removing those as well, I still get an error when opening the workbook.
My question
Apart from conditional formatting, validation lists, VBA code, and formulas linking a worksheet that was pasted to a new workbook, what other elements could cause the workbook from opening in repair mode every time due to existing links to the old workbook?
If my question is not clear, comment and I will clarify.
Dealing directly with VBE seems a bit heavy-handed to me. If your code is manipulating several workbooks, I would put the code in an add-in and not have it in any workbook. (Technically *.xlam addins are workbooks, but when I say "workbook" I mean normal *.xls, *.xlsx, *.xlsm, etc.)
That said, if you're just copying cell values (which may be formulas) between different workbooks, you shouldn't have any dependencies other than cell references, named ranges, and user-defined functions in the original workbook. I would make sure there are none of those. Please also share how you are ensuring your formulas do not have broken references.
If the issue you are having is caused by trying to avoid hidden columns and rows not allowing pastevalues, why not unhide the rows and columns and then copy only the values to the new book?
Just cycle through each of the sheets in the original book and use the method .UsedRange.Hidden = False. As far as I am aware, this should unhide every cell on the sheet and allow you to do the original pastevalues calls
This works fast and smooth (it's harder to delete ALL the data Imo):
Sub tests()
Dim AllRange As Range: Set AllRange = ActiveSheet.UsedRange
Dim ItemRange As Range
Dim myWbDestination As Workbook: Set myWbDestination = ThisWorkbook
Dim SheetDestination As String: SheetDestination = ("Sheet2")
For Each ItemRange In AllRange
With myWbDestination.Sheets(SheetDestination)
.Range(ItemRange.Address) = ItemRange.Value
End With
Next ItemRange
End Sub
Repair mode can be triggered by many factors, you would need to post the code you are getting to look for an explanation, it would be like asking why vba may broke

VBA - Copying worksheet from one workbook to another (values, not formulas)

Currently, I am copying the values and formats of a worksheet to a worksheet in another workbook as such:
workbooks("book1.xlsm").sheets(1).range(someRange).copy
with workbooks("book2.xlsm").sheets(1).range("A1")
.pasteSpecial xlPasteValues
.pasteSpecial xlPasteFormats
end with
I would like to use something like:
workbooks("book1.xlsm").sheet(1).copy after:=workbooks("book2.xlsm").sheet(1)
The problem is that some of the cells in sheet(1) of book1.xlsm have formulas. Using the second method pulls the formulas, and the resulting values are linked to the data in book2.xlsm
How can I use the second method, but have the values, not formulas, copied?
If not possible, what are some alternatives, aside from the first method, which I am currently using?
You can break the links after the copy operation:
Option Explicit
Sub copySheetValues()
With Workbooks("Book2")
Workbooks("Book1").Worksheets(1).Copy After:=.Worksheets(1)
Application.Wait Now + TimeValue("0:00:01") 'built-in replacement for "Sleep"
.BreakLink Name:=Workbooks("Book1.xlsm").FullName, Type:=xlLinkTypeExcelLinks
End With
End Sub
Note: both files need to be open in the same instance of the Excel application

Run time Error - 438

I have the following code in which I am trying to copy data from one sheet to another in same workbook. When I run the code I get Runtime error -438
Sub Copy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet2").Activate
Range("E1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Try the following code. You should not rely on Activate and Select.
Sub ZCopy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet1").Paste Destination:=Worksheets("Sheet2").Range("E1")
Application.CutCopyMode = False
End Sub
Interesting Reads
MSDN
How to avoid using Select in Excel VBA macros
Do you have a particular need for copy and paste? This can be slow and inefficient. If you're just copying data from one sheet to another, you can set the values of one range equal to the values of another range and avoid the whole thing.
Sheets("Sheet2").Range("E1:H20").Value = Sheets("Sheet1").Range("A1:D20").Value
This will set the range from cells E1:H20 on Sheet2 to the same values as those in the range A1:D20 on Sheet1, which is effectively a copy and paste. I should add that this will work only for the values themselves.
If there is specific formatting (or formulas) that you need copied and pasted, this method won't work.

How do I open a worksheet in vba?

Hilariously the following code only works if the worksheet is actually selected in the excel window. I really want to finish this macro soon but can't seem to work out how to select a specific worksheet so it is open in excel? Many thanks if someone knows how. I have to use range and so on.
sheet.Range(Cells(firstRow, 2).Address(False, False), Cells(lastRow, 50)).Select
With Selection
.Copy
End With
sheet.Range(Cells(firstRow, 3).Address(False, False), Cells(lastRow, 51)).Select
With Selection
.PasteSpecial xlPasteValuesAndNumberFormats
End With
You can activate the worksheet by name or by 1-based index (the number -- 1st workbook, 2nd, and so on). The syntax is the same, either way.
This will activate the 3rd worksheet:
ActiveWorkbook.Sheets(3).Activate
This will activate the worksheet named stats:
ActiveWorkbook.Sheets("stats").Activate
Of course, you don't have to actually make the worksheet selected in the Excel window to work with it. Your code uses a variable called sheet, which I assume you've assigned to the active worksheet. Instead of doing that, you can set sheet = ActiveWorkbook.Sheets("stats"), and then work with the sheet even if is not in view.
Workbooks(x).Worksheets(x).Activate ?