Copying and pasting from Macro workbook to multiple workbooks Excel - vba

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

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

Unable to paste into a protected worksheet using VBA, but can do it manually

I have written a macro that should copy a range of data from one workbook into another. The sheet in the other workbook is password protected, but if I copy and past manually, it allows me to do so. However, when I try and write this into my macro, it won't allow the paste.
Code is currently as follows:
Sub COPYT()
'
' COPYT Macro
Range("B2:U109").Select
Selection.Copy
Workbooks.Open Filename:= _
"_FileName_.xls"
Windows("_FileName_.xls").Activate
Range("H10").Paste
End Sub
When I run the macro as is, I get a
Run-time error '438': "Object doesn't support this property or method"
and the debugger shows that the issue is with the last line Range("H10").Paste
I can't unprotect the sheet (compliance), and I can obviously get round this by just running the macro and then CTRL+V but (as this allows me to paste....), but I would rather that this was automated. Do I need a different syntax for the paste command due to the sheet being protected?
Thanks
Paste is a method of the worksheet, not range. Try this. I have assumed sheet references but you may need to adjust.
Sub COPYT()
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="_FileName_.xls")
wb.Sheets("compliance").unprotect
ThisWorkbook.Sheets(1).Range("B2:U109").Copy wb.Sheets("compliance").Range("H10")
wb.Sheets("compliance").protect
End Sub

Excel - copy from another workbook with conditional formatting intact

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

Linking un-named workbook to variable in VBA

I am writing a macro that will copy and paste information form one workbook into another workbook in excel 2010. The workbook that the data is in is the same workbook as the macro. I have made VBA create a new workbook to paste the data in. How do I assign the new workbook that VBA has just created to a variable.
Thanks For Any Help
You haven't mentioned exactly how you create the workbook, but you can set a reference to the new Workbook object in the same statement that creates it.
Example:
Option Explicit
Sub AddWorkbook()
Dim oWb As Workbook
Set oWb = Workbooks.Add
'Do something with the new workbook
Debug.Print oWb.FullName
Set oWb = Nothing
End Sub
try seeing names of all workbooks by iterating over Workbooks. I think the name of newly created workbook will "Workbook1" until there is already no other unnamed workbook. So basically newly created workbook is still not unnamed.

Excel 2010 VBA running in all opened files

I have one excel file (*.xlsm) with VBA code on first sheet:
Private Sub Worksheet_Calculate()
ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
End Sub
And second excel file with macro that is changing value in cell in first excel (it is automaticaly recalculated) and then copy value of new result from first excel and paste it to second excel file.
Problem is: when macro is going to second excel and paste value, worksheet is recalculated and code from first excel is calling, but it stops with error because in second excel it cant find chart object "Podtlak".
How to set worksheet_calculate() to run only for file whitch one is it written?
Try specifying the workbook:
ThisWorkbook.ActiveSheet.ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
Or specifying the worksheet and workbook:
ThisWorkbook.Worksheets("yourWorksheetName").ChartObjects("Podtlak").Chart.Axes(xlCategory, xlPrimary).MaximumScale = Range("AV79").Value
I like the 2nd option best as you are clearly specifying the worksheet and workbook that this function runs on. Anytime you use ActiveSheet or ActiveWorkbook, you are relying on the fact that your intended worksheet is active when the code runs.