Excel - copy from another workbook with conditional formatting intact - vba

I've figured out most of this myself, but the part that is hanging me up is being able to paste the conditional formatting.
I want to be able to have a workbook open, run a VBA script to open another workbook, copy a range from it, then paste that to the original workbook.
The most success I've had is recording the macro and make this happen:
With the original, target workbook open...
Open the source workbook
Copy range A1:X105
Close source workbook
Paste into worksheet titled "Temp" in target workbook
The problem is that the source workbook contains conditional formatting, and if the source workbook is closed before you paste into the target workbook, the conditional formatting isn't being pasted.
So either I need to find a way to paste the data with the conditional formatting, or I need to be able to switch back to the target workbook before closing the source workbook. This is a process that is going to need to be ran multiple times with different target workbooks, so the VBA code can't refer to a workbook filename for the target. The source workbook will always have the same path though.
Searching the site, I could only find solutions that specified the path for both workbooks.
This is what I have right now:
Sub CopyData()
Application.DisplayAlerts = False
Workbooks.Open filename:="source.xlsx", _
UpdateLinks:=3
Range("A1:X105").Select
Selection.Copy
ActiveWindow.Close
Sheets("Temp").Select
ActiveSheet.Paste
Application.DisplayAlerts = True
End Sub
I suppose what I need to implement into this is to declare the target workbook as a variable. Can someone help with that?

You can just dim the workbook and then copy and paste. After you have completed that you can then using the variable, close the workbook. Code would be as follows:
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
ThisWorkbook.ActiveSheet.Selection.Paste
wbSource.Close
Application.DisplayAlerts = True
End Sub
I don't see how you determine what range you paste on the target workbook but will leave that for another question. The answer by Emily Alden I don't think will work because you can't copy from a source that is closed. Clipboard behaves differently with Excel than with other applications.

Based on new information:
Sub CopyData()
Application.DisplayAlerts = False
Workbooks.Open filename:="source.xlsx", _
UpdateLinks:=3
Range("A1:X105").Select
Selection.Copy
ActiveWindow.Close
Sheets("Temp").Select
ActiveSheet.PasteSpecial xlPasteFormats
Application.DisplayAlerts = True
End Sub
Previous:
From:Copy conditional formatting from one cell to another using VBA?
Sub test()
Sheets("B").[B1].Copy: Sheets("A").[A1:A10].PasteSpecial xlPasteFormats
End Sub
Is a code that will paste the conditional formatting.
Mostly what you need to do is change the order:
Open Source using a Prompt for the User to select file
Copy Range from Source
Paste Range to Original
Close Source

Related

Copy and combine sheets to a workbook

I need VBA code for Excel which: will be activated by a button in an empty workbook, loop through open workbooks, copies only sheets called "specificsheetname" from workbooks and pastes it into a new worksheet in the button activator workbook. So idea is that it will combine many worksheets from different workbooks into a one workbook. I tried this:
Sub workbookFetcher()
Dim book As Workbook, sheet, wsNew, wsCurr As Worksheet
Set wsCurr = ActiveSheet
For Each book In Workbooks
For Each sheet In book.Worksheets
If sheet.Name = "COOLING_RAW" Then
Set wsNew = Sheets.Add(After:=wsCurr)
book.Worksheets("COOLING_RAW").Copy
Set wsNew = book.Worksheets("COOLING_RAW")
End If
Next sheet
Next book
End Sub
It kind of works but it pastes all the copied worksheets to a new workbook. That's not what I want, I want them to pasted in the same workbook.
As I said in my comment:
Sub workbookFetcher()
Dim book As Workbook, sheet as Worksheet
For Each book In Workbooks
For Each sheet In book.Worksheets
If sheet.Name = "COOLING_RAW" Then
book.Worksheets("COOLING_RAW").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End If
Next sheet
Next book
End Sub
If you want it to be after the ActiveSheet and the ActiveSheet is in the middle of other sheets, you can still use your wsCurr and just increment the index.
If you've got Excel 2016, then the newly bundled PowerQuery functionality under the Get & Transform part of the ribbon is by far the best way to do this. Suggest you google something like PowerQuery Combine Workbooks and you'll see heaps of great tutorials showing you exactly what to do. It pretty much makes lots of VBA redundant, and it is childs-play to learn compared to VBA.
If you've got any other version of Excel from 2010 up and have admin rights on your machine, you can download and install PowerQuery from Microsoft's site...it's a free add-in
you don't need to iterate through each single workbook worksheets, while you just try to get the wanted sheet and copy it if it actually exists
moreover you want to avoid searching ThisWorkbook itsel for wanted worksheet, too!
Option Explicit
Sub workbookFetcher()
Dim book As Workbook, sht As Worksheet
For Each book In Workbooks
If book.Name <> ThisWorkbook.Name Then ' skip ThisWorkbook and avoid possible worksheet duplication
If GetWorksheet(book, "COOLING_RAW", sht) Then sht.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) ' if currently searched workbook has wanted worksheet then copy it to ThisWorkbook
End If
Next
End Sub
Function GetWorksheet(book As Workbook, shtName As String, sht As Worksheet) As Boolean
On Error Resume Next ' prevent subsequent statement possible error from stoping the function
Set sht = book.Worksheets(shtName) ' try getting the wanted sheet in the passed workbook
GetWorksheet = Not sht Is Nothing ' return 'True' if successfully got your sheet in the passed workbook
End Function

PasteSpecial of Range class failed

I am trying to select copy everything from a "database" workbook. and paste it in the current workbook, sheet 5. The code I am using is the following.
Sub Import()
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy 'Copy everything from the database
Sheet5.Range("A1").PasteSpecial xlPasteAll 'Paste everything in sheet 5 of current workbook
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
End Sub
I am receiving an error when running the following code. Though, sometimes it doesn't give me an error.
Run-time error '1004': PasteSpecial method of Range class failed
I think I know why it's giving me an error at the PasteSpecial line. When I have a different cell selected in sheet 5, it gives me no error. but when I recheck, without selecting any other cell, (so it will have the pasted range selected), I get this error.
I tried using the following line between copy and pastespecial,
Sheet5.range("A1").select
it gives me the same error.
----------UPDATE----------
I first used DisplayName's solution and it worked until yesterday. But this morning, it was causing problems. It another error. Then I tried all other solutions with no luck. all gave me the same errors. I also added the workbook.worksheet to the solutions below giving me no luck. This time the error was with the copy method. I also noticed that lots of columns say #REF.
Versions I tried:
DisplayName's solution combined with thisworkbook.worksheet
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=ThisWorkbook.Sheets(5).Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
Gary's Student's solution combined with thisworkbook.worksheet
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Dim Destination As Worksheet
Set DestinSh = ThisWorkbook.Sheets(5)
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy DestinSh.Range("A1").PasteSpecial 'copy database info in planning tool.
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
errors:
Run-time error '1004': Copy method of Range class failed
First insure that there are no merged cells on either worksheet, and then try:
DBaseSheet.UsedRange.Copy Sheet5.Range("A1")
you could simply go:
Sub Import()
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=Sheet5.Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
End Sub
I am with Bruce Wayne on this one
As you have opened a new workbook the focus is now on that workbook.
If you are trying to clear the cells in the workbook the code resides in (destination) after you have launched a new workbook and switched the focus you will need to reference the original workbook to do so, like this:
ThisWorkbook.Sheets(5).Cells.Clear
Hope this helps

Locking Worksheet

I am using Excel 2013, and have a macro that copies a "master" worksheet to the end of the workbook, once filled in by the user. The worksheet that's copied, is renamed, according to the "master" report number. Is there a way that once the sheet is copied to the end, it can be locked so the user can not make any changes to it. I just want them to be able to view it. I've researched some sample code online, but nothing seems to do what I am trying to do. Anyone have any ideas or can help? Much thanks
You can use the .Protect and .Unprotect properties. Below is an example sub that protects all worksheets, charts in a workbook and then protects the workbook itself. Here's a site with more detailed info, and it would also be good to review how items are protected in Excel generally.
Sub protectWk(wk As Workbook)
Dim sh as Worksheet, ch as Chart
For Each sh In wk.Worksheets
sh.Protect ("password")
Next
For Each ch In wk.Charts
ch.Protect ("password")
Next
wk.Protect ("password")
wk.Close SaveChanges:=True
End Sub

Copying and pasting from Macro workbook to multiple workbooks Excel

I am creating a macro that will process and format scans (SCANfile#.xlm) saved as .xlm files The end result should be a processed, formatted workbook that will be saved as an Excel file. I am creating the macro in a workbook I will call SCANMacro for the purpose of this discussion with the intention of it being open simultaneously with whichever SCANfile# workbook I may have open at the time.
Sub Copy and Paste Data ()
'select cell on target workbook/worksheet
Range("X1").Select
'
'select the data from the saved workbook that the macro runs from
'
Columns("SCAMNmacro.xlsm C:G").Select
Selection.Copy
'
'Paste into SCANfile#.xlm.xml
'
Windows("SCANFILE01.xml").Activate
Range("X1").Select
ActiveSheet.Paste
End Sub
This works fabulously as long as I run it from the SCANfile01.xml I had opened as I created it. As soon as I open the Macro enabled workbook with a different scanfile, it errors out.
How do I set this up so that the Macro works on any ScanSheet? I tried working with Thisworkbook and Activeworkbook to no avail. I am not a programmer so most of this has been recorded with me tweaking inside the VBA editor.
Use Workbook variables for referencing the proper Workbooks:
Dim MacroSheet as Workbook
Set MacroSheet = ThisWorkbook
Dim ScanFile as Workbook
Set ScanFile = Workbooks.Open("PATH TO YOUR FILE")
Then you can use it like this:
MacroSheet.Columns("G").Copy

Paste sheet copied from an open workbook into an existing non open workbook

I am trying to copy "Sheet1" from the workbook I have open, labelled "source.xlsm", and paste after the last sheet of my existing workbook which is not open at the time of running, labelled "target.xlsx".
I have the below code and it seems the whole "C:\" directory does nothing. Is it even possible to put a directory in? I cannot find a way to do this without having the Target.xlsx open.
ActiveSheet.Select
ActiveSheet.Copy After:=Workbooks("C:\Target.xlsx").Sheets("FirstSheet")
You already figured it out, but a suggested edit:
Dim wb As WorkBook
''Open 2nd Workbook
Set wb = Workbooks.Open(Filename:="C:\Archive.xlsx")
''Copy To Different Workbook
Workbooks("Source.xlsx").Sheets("Source").Copy _
After:=wb.Sheets("Archive")
''Close 2nd Workbook
wb.Save
wb.Close
Answered my own question with the helpful information provided by Tim.
''Open 2nd Workbook
Workbooks.Open Filename:="C:\Archive.xlsx"
''Copy To Different Workbook
Workbooks("Source.xlsx").Sheets("Source").Activate
ActiveSheet.Copy After:=Workbooks("Archive.xlsx").Sheets("Archive")
''Close 2nd Workbook
Workbooks("Archive.xlsx").Sheets("Archive").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close