VBA Copy and Paste Formatting for all Worksheet - excel

I try to write really simple script to copy original worksheet (ORIGINAL_NOCHANGE) and paste the formatting only other sheet.
In the ORIGINAL_NOCHANGE, there are some column merged together, and some column having the conditional formatting.
This is the original structure of ORIGINAL_NOCHANGE :
COPY1 and COPY2 are the copy of ORIGINAL_NOCHANGE, but has no format like the original one (my Python script cannot copy the Excel formatting).
After I run my VBA script :
Sub TrySecond()
Dim ws As Worksheet
'Worksheets("ORIGINAL_NOCHANGE").Activate
Worksheets("ORIGINAL_NOCHANGE").Range("A1:AA71").Copy
For Each ws In Worksheets
If ws.Name <> "ORIGINAL_NOCHANGE" Then
'ws.Range("AC1") = "Are You Kidding Me"
Range("A1:P17").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End If
Next
End Sub
the ORIGINAL_NOCHANGE has been changed into this structure, which I really don't want :
but nothing happend in COPY1 and COPY2!
Note that my python script will copy hundreds of ORIGINAL_NOCHANGE worksheet but due to the limitation of package inside, it couldn't copy the formatting.
Putting here as somebody might be suggesting me to copy the original manually.
I'm not sure what's the mistake in my script. Can you please help?
Thanks a lot!

Formats to New Worksheets
Adjust the values in the constants section (and the workbook).
Option Explicit
Sub FormatsToNewWorksheets()
' Define constants.
Const sName As String = "ORIGINAL_NOCHANGE"
Const dNamesList As String = "COPY1,COPY2"
' Create a reference to the workbook containing this code.
Dim wb As Workbook: Set wb = ThisWorkbook
' Create a reference to the Source Worksheet.
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
' Write the names from the list to the Destination Names Array.
Dim dNames() As String: dNames = Split(dNamesList, ",")
' Declare additional variables.
Dim dws As Worksheet ' (Current) Destination Worksheet
Dim n As Long ' Destination Names Counter
' Loop through the elements (names) of the Destination Names Array.
For n = 0 To UBound(dNames)
' Attempt to create a reference to the (current) Destination Worksheet.
On Error Resume Next
Set dws = wb.Worksheets(dNames(n))
On Error GoTo 0
' Delete the (current) Destination Worksheet if it exists.
If Not dws Is Nothing Then ' exists
Application.DisplayAlerts = False
dws.Delete
Application.DisplayAlerts = True
'Else ' doesn't exist
End If
' Create the (current) Destination Worksheet
' (a copy of the Source Worksheet)
' after all existing sheets (at the last position).
sws.Copy After:=wb.Sheets(wb.Sheets.Count)
' Modify the (current) Destination Worksheet.
With ActiveSheet
.Name = dNames(n)
.UsedRange.ClearContents ' or not?
End With
Next n
End Sub

Right click on your worksheet, and select Move or Copy then tick create a copy, then you can create as many sheets as you want with the same format without VBA ....and you can create this worksheet to other workbook also....
If you still prefer VBA code, here is the function you can use, same as what i am doing just now:
Sub Macro1()
Sheets("Sheet1").Select
Sheets("Sheet1").Copy After:=Sheets(1)
End Sub

Related

How to copy-paste from one specific workbook to multiple workbook with different names? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Sub Macro1()
'
' Macro1 Macro
'
'
Windows("Formats.xlsx").Activate
Range("A1:D3").Select
Selection.Copy
Windows("ABCD.xlsx").Activate `need correction here, because I have to paste it on different workbooks with multiple sheets`
Range("D3").Select
ActiveSheet.Paste
End Sub
Hello, I am trying to copy a range ("A1:D3") from one workbook to multiple workbooks (different names) in which contains multiple sheets (different names). Can anyone help me on this matter? Thanks in advance.
Copy Range to Multiple Worksheets in Multiple Workbooks
Macro-Recorder
To receive a useful answer, you need to let us know the necessary details. The macro-recorder is a great tool but it's not perfect i.e. it often doesn't behave as we want it to.
In this particular case, your code doesn't tell us where the files are located because you didn't record this part. It doesn't tell us the worksheet names because they are the active ones. It doesn't tell us to save and close the workbooks because you didn't record this part. To work around this, you need to properly record the macro and manually add a few basic lines (see the comments in the code (manually added)).
If you look at the macro-recorder code, you will notice that almost all the necessary information to write a proper code is in it and any newb could understand most, if not all of it. Additionally, you should explain what the code doesn't show e.g. you want it to work for all files in the folder.
Proper Code Benefits
The proper code will loop through all .xlsx worksheets (not just two specific) in the folder.
It won't select anything it will just reference the objects (workbook, worksheet, range...) making it more efficient (faster).
Also, by using constants at the beginning of the code, it is quite easy to modify the various values and make it work for a similar yet different scenario.
Macro-Recorder Code
Sub Macro1()
'
' Macro1 Macro
'
'
' How to Record a Useful Macro
' 1. Close all related files.
' 2. Start recording.
' 3. Open the Source file (Ctrl+O),...
Workbooks.Open Filename:="C:\Test\Formats.xlsx"
' ... select the worksheet,...
Sheets("Sheet1").Select ' manually added
' ... select the range,...
Range("A1:D3").Select
Application.CutCopyMode = False ' automatically added before copy
' ... and copy the range (Ctrl+C).
Selection.Copy
' 4. Open the 1st Destination file (Ctrl+O),...
Workbooks.Open Filename:="C:\Test\MyWorkbooks\ABCD.xlsx"
' ... select the 1st worksheet,...
Sheets("Sheet1").Select ' manually added
' ... select the first cell...
Range("D3").Select
' ... and paste (Ctrl+V),...
ActiveSheet.Paste
' ... select the 2nd worksheet,...
Sheets("Sheet2").Select
' ... select the first cell,...
Range("D3").Select
' ... paste (Ctrl+V),...
ActiveSheet.Paste
' ... save the file (Ctrl+S)...
ActiveWorkbook.Save
' ... and close it (Ctrl+W).
ActiveWorkbook.Close
' 4. Open the 2nd Destination file (Ctrl+O),...
Workbooks.Open Filename:="C:\Test\MyWorkbooks\EFGH.xlsx"
' ... select the 1st worksheet,...
Sheets("Sheet1").Select ' manually added
' ... select the first cell...
Range("D3").Select
' ... and paste (Ctrl+V),...
ActiveSheet.Paste
' ... select the 2nd worksheet,...
Sheets("Sheet2").Select
' ... select the first cell,...
Range("D3").Select
' ... paste (Ctrl+V),...
ActiveSheet.Paste
' ... save the file (Ctrl+S)...
ActiveWorkbook.Save
' ... and close it (Ctrl+W).
ActiveWorkbook.Close
' 5. Activate the Source file...
Windows("Formats.xlsx").Activate ' manually added
' ... and close it (Ctrl+W).
ActiveWorkbook.Close
' 6. Stop recording.
End Sub
Proper Code
Sub CopyRange()
' Define constants.
Const SRC_FILE_PATH As String = "C:\Test\Formats.xlsx"
Const SRC_WORKSHEET As String = "Sheet1"
Const SRC_RANGE As String = "A1:D3"
Const DST_FOLDER_PATH As String = "C:\Test\MyWorkbooks\"
Const DST_FIRST_CELL As String = "D3"
Const DST_PATTERN As String = "*.xlsx"
Dim dSheetNames(): dSheetNames = Array("Sheet1", "Sheet2")
' Reference the source range ('srg').
Dim swb As Workbook: Set swb = Workbooks.Open(SRC_FILE_PATH)
Dim sws As Worksheet: Set sws = swb.Sheets(SRC_WORKSHEET)
Dim srg As Range: Set srg = sws.Range(SRC_RANGE)
' Get the first Destination file name.
Dim dFileName As String
dFileName = Dir(DST_FOLDER_PATH & "*" & DST_PATTERN)
Application.ScreenUpdating = False
Dim dwb As Workbook, dws As Worksheet, dfCell As Range, dSheetName
' Open each file in the folder and copy the Source range
' to the worksheets from the list (array i.e. 'dSheetNames').
' and save and close it.
Do While Len(dFileName) > 0
Set dwb = Workbooks.Open(DST_FOLDER_PATH & dFileName)
For Each dSheetName In dSheetNames
Set dws = dwb.Sheets(dSheetName)
Set dfCell = dws.Range(DST_FIRST_CELL)
srg.Copy dfCell
Next dSheetName
dwb.Close SaveChanges:=True
dFileName = Dir ' next file
Loop
Application.ScreenUpdating = True
' Inform.
MsgBox "Range copied.", vbInformation
End Sub

VBA Excel - copy object to last active sheet

I have an object located on a different sheet, which I would like to copy to the last active sheet. Unfortunately, the code I have throws an error:
Object doesn't support this property or method
Sub AddCabinet()
Dim MooSheet, CurrentSheet As Worksheet
Set CurrentSheet = ThisWorkbook.ActiveSheet
Set MooSheet = ThisWorkbook.Sheets("Cab Templates")
MooSheet.Shapes.Range(Array("VHPOPA")).Select
Selection.Copy
CurrentSheet.Range("A1").Paste
End Sub
How can I copy an object to my previous current sheet? I have a few sheets with the same buttons.
.paste is a worksheet method, not a range method, that is where the error is coming from.
We can remove all the Selects to make this a bit cleaner.
Dim MooSheet As Worksheet, CurrentSheet As Worksheet
Set CurrentSheet = ThisWorkbook.ActiveSheet
Set MooSheet = ThisWorkbook.Sheets("Cab Templates")
MooSheet.Shapes("VHPOPA").Copy
CurrentSheet.Paste
Copy Shapes
Can you even get rid of Select and Activate when copying multiple shapes? I couldn't.
My idea was to copy the shape(s) and restore the worksheets initial selections.
The array is useful to copy multiple shapes. Note that if you don't explicitly use the array function as the parameter for the Shape.Range property, you need to evaluate the array by putting it into parentheses, if its variable is declared as a variant without parentheses i.e.:
Dim shpArr() As Variant... sws.Shapes.Range(shpArr).Select
' or:
Dim shpArr As Variant ... sws.Shapes.Range((shpArr)).Select
The Flow
Exit if the workbook containing this code (ThisWorkbook) is not the active workbook (ActiveWorkbook). Exit if the active sheet (ActiveSheet) is not a worksheet. Reference the active sheet i.e. the destination worksheet.
Reference the source worksheet. Exit if it's the destination worksheet.
Reference the destination Selection to restore after the job is done. Reference the destination cell. Activate it, if it's not active.
Select the source worksheet. Reference its Selection to restore it after the job is done. Select all shapes whose names are in the array and copy them using Selection.
Activate the destination worksheet and paste. Restore its initial selection using Select.
Select the source workbook to restore its initial selection using Select.
Select the destination worksheet.
Sub AddCabinet()
' Define constants.
Const sName As String = "Cab Templates"
Const dFirstCellAddress As String = "A1"
Dim shpArr() As Variant: shpArr = Array("VHPOPA")
'Dim shpArr() As Variant: shpArr = Array("Oval 1", "Oval 2")
' Reference ThisWorkbook's active sheet, the destination worksheet ('dws').
Dim wb As Workbook: Set wb = ThisWorkbook
If Not wb Is ActiveWorkbook Then Exit Sub ' another workbook is active
If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
Dim dws As Worksheet: Set dws = wb.ActiveSheet ' or 'ActiveSheet'
' Reference the source worksheet ('sws')
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
If sws Is dws Then Exit Sub ' source and destination are the same
'Application.ScreenUpdating = False
' Reference the destination cell ('dCell') and activate if not active.
Dim dSel As Object: Set dSel = Selection ' store
Dim dCell As Range: Set dCell = dws.Range(dFirstCellAddress)
If Not dCell Is ActiveCell Then dCell.Activate ' ensure it's active
' Copy.
sws.Select
Dim sSel As Object: Set sSel = Selection ' store
sws.Shapes.Range(shpArr).Select
Selection.Copy
' Paste.
With dws
.Activate
.Paste
End With
If Not dSel Is Nothing Then dSel.Select ' restore
sws.Select
If Not sSel Is Nothing Then sSel.Select ' restore
dws.Select
'Application.ScreenUpdating = True
End Sub
Before copying the object need to be there in that sheet, solve the problem...
try this...
Sub AddCabinet()
Dim MooSheet, CurrentSheet As Worksheet
Set CurrentSheet = ThisWorkbook.ActiveSheet
Set MooSheet = ThisWorkbook.Sheets("Cab Templates")
MooSheet.Select
MooSheet.Shapes.Range(Array("VHPOPA")).Select
Selection.Copy
CurrentSheet.Select
Range("A1").Select
ActiveSheet.Paste
End Sub
Hope it Helps...

How can I design the code in VBA in order to refer to a previously already newly created workbook in Excel?

How can I refer in VBA to a previously newly created workbook within the same macro? For example, I copy something from A2 in the active workbook, then I create a new workbook, paste there in cell B3, return to the first workbook, copy cell A3, return again to the newly created workbook and paste in in cell B4.
So, what I need is the code for this part of the sentence: "return again to the newly created workbook"
My code till now is this:
`Selection.Copy`
`Workbooks.Add`
`Range("B3").Paste`
`Windows("First_WorkBook.xlsm").Activate`
`Range("A3").Select`
`Selection.Copy`
The last two lines are missing: returning to the new workbook and pasting there.
Can you please help me with this issue?
Please, try the next code. You should also declare the sheets where the ranges will be copied:
Sub testNewWBCopy()
Dim actWb As Workbook, newWb As Workbook, shAct As Worksheet, shNew As Worksheet
Set actWb = ActiveWorkbook
Set shAct = actWb.Sheets(1)
Set newWb = Workbooks.Add
Set shNew = newWb.Sheets(1)
shAct.Range("A2").Copy Destination:=shNew.Range("B3")
shAct.Range("A3").Copy Destination:=shNew.Range("B4")
End Sub
And it is good to avoid selecting, activating, if possible... They only consume Excel resources and make the code slower.
Copy from One Worksheet to Another (in a Different Workbook)
Using variables will do the trick.
Option Explicit
Sub CopyCells()
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets("Sheet1")
' Source
Dim swb As Workbook: Set swb = Workbooks("First_Workbook.xlsm")
' To avoid an error occuring if the workbook is not open, you could
' replace the previous line with the following code block:
' On Error Resume Next
' Dim swb As Workbook: Set swb = Workbooks("First_Workbook.xlsm")
' On Error GoTo 0
' If swb Is Nothing Then
' MsgBox "The workbook is not open.", vbCritical, "CopyCells"
' Exit Sub
' End If
Dim sws As Worksheet: Set sws = swb.Worksheets("Sheet1")
' Copy
sws.Range("A2").Copy
dws.Range("B2").PasteSpecial
sws.Range("A3").Copy
dws.Range("B3").PasteSpecial
Application.CutCopyMode = False
' In this particular case you would rather do:
' sws.Range("A2:A3").Copy
' dws.Range("B2:B3").PasteSpecial
' Application.CutCopyMode = False
' Or:
'sws.Range("A2:A3").Copy dws.Range("B2:B3")
' Or (for copying values only):
'dws.Range("B2:B3").Value = sws.Range("A2:A3").Value
End Sub

copy and paste error causing workbook to crash

I'm having an issue with copy and pasting from one spreadsheet to another.
I am using the following code:
Sub LoadnH()
Dim NF As Workbook
Dim shtMain As Worksheet
Set shtMain = Worksheets("Main")
Dim filePath As String
Dim strFileName As Variant
strFileName = Application.GetOpenFilename("All Files (*.*), *.*", , "Select File to Import", , False)
shtMain.Range("filePath").Value = strFileName
If strFileName <> False Then
Set NF = Application.Workbooks.Open(strFileName)
Application.CutCopyMode = False
NF.Sheets("Summary").Copy
Application.DisplayAlerts = False
NF.Close False
Dim nH As Worksheet
Set nH = Worksheets("Hedge Data")
nH.Activate
With nH
.Cells.Clear
.Pictures.Delete
.Range("A1").Select
.PasteSpecial xlPasteValues
End With
End If
End Sub
The code errors out at the following point
.PasteSpecial xlPasteValues
The code show a runtime error '1004':
Method 'PasteSpecial' of object'_Worksheet' failed
how can I fix this so this error? Many times when it hits this error excel will crash and shutdown as well.
To Avoid Select and other similar methods you can assign your value of the destination range with the value from your source range.
You are using the Worksheet.Copy method which copies an entire Worksheet not the data in a Range of the worksheet. This will be creating a new copy of your source worksheet each time you run the code but not copying the data of the worksheet to the clipboard. (NB: below demonstrates using the Before parameter which dictates where the Worksheet will be copied to).
The Range.Copy method will copy the defined range's data to the clipboard (unless you specify the destination parameter).
Rather than using Copy/Paste etc. you can assign the value of the destination range with the value from your source range.
These examples below are all for demonstration of the above points and are tested using 2 new workbooks with default names for the workbooks and worksheets.
E.g 1
Sub WorksheetCopyMethod()
Dim SourceWorksheet As Worksheet
Dim DestinationwWorksheet As Worksheet
Set SourceWorksheet = Workbooks("Book1").Sheets("Sheet1")
Set DestinationWorksheet = Workbooks("Book2").Sheets("Sheet1")
SourceWorksheet.Copy DestinationWorksheet
End Sub
The result of this test creates a copy of Sheet1 from Book1 before Sheet1 on Book2.
E.g 2
Sub RangeCopyMethod()
Dim SourceWorksheet As Worksheet
Dim DestinationwWorksheet As Worksheet
Set SourceWorksheet = Workbooks("Book1").Sheets("Sheet1")
Set DestinationWorksheet = Workbooks("Book2").Sheets("Sheet1")
SourceWorksheet.Range("A1").Copy
DestinationWorksheet.Range("A1").PasteSpecial xlPasteValues
End Sub
This example copies cell A1 from Book1 - Sheet1 and pastes it to cell A1 in Book2 - Sheet1.
E.g 3
Sub AvoidSelectMethod()
Dim SourceWorksheet As Worksheet
Dim DestinationwWorksheet As Worksheet
Set SourceWorksheet = Workbooks("Book1").Sheets("Sheet1")
Set DestinationWorksheet = Workbooks("Book2").Sheets("Sheet1")
DestinationWorksheet.Range("A1").Value = SourceWorksheet.Range("A1").Value
End Sub
This example assigns the Value property of A1 from Book1 - Sheet1 to cell A1 in Book2 - Sheet1. It's the same outcome as E.g 2 but avoids using Select, Copy & Paste etc. This method is much faster and generally less error prone than the 2nd example.
Depending on your environment, the first example may be the easiest and quickest method.

VBA focus passing

trying to do in another focus with the window from the workbook from first trying to do in another focus with the window from the workbook from first
Sub Update_DHL()
Workbooks.Open Filename:=trk
Workbooks.Open Filename:=stp
Workbooks.Open Filename:=dhl
Windows(stp).Activate
Workbooks(stpfile).Activate
Range("B2").Select
ActiveCell.Formula = _
"Hi"
Range(Cells(2, 2), Cells(2, 2)).Copy
'Range(Cells(3, 2), Cells(65536, 45)).Select
'Selection.ClearContents
'Range(Cells(3, 47), Cells(65536, 74)).Select
'Selection.ClearContents
' Set wb = Workbooks("VMW Macro.xlsm") 'Name of the workbook you are copying from
' Set ws = wb.Sheets("Extract") 'Name of sheet you are copying
' DateStamp = Format(Now(), "mm-dd-yyyy hhmmss")
End Sub
Make sure you define variables for your workbooks and worksheets properly. You can then use them for your Range and Cells objects to specify in which workbook and worksheet they are. This way you don't need .Activate or .Select because the code even works if the workbook has no focus.
Make sure in your entire code there is no Range and Cells object without a workbook and worksheet specified. Either by using a variable like shown below. Or directly like ThisWorkbook.Worksheets("Sheet1").Range(…).
You only need to .Activate or .Select if you want to focus it for the user. You never need to do this to make VBA work properly (VBA can work with non-focused workbooks/worksheets).
Option Explicit
Sub Update_DHL()
'open your workbooks
On Error GoTo ERR_WB_OPEN
Dim wbTrk As Workbook
Set wbTrk = Workbooks.Open(Filename:=[truckfilePath])
Dim wbStp As Workbook
Set wbStp = Workbooks.Open(Filename:=[stopfilePath])
Dim wbDhl As Workbook
Set wbDhl = Workbooks.Open(Filename:=[dhlfilePath])
On Error GoTo 0
'define in which worksheet in those workbooks you want to work
Dim wsTrk As Worksheet
Set wsTrk = wbTrk.Worksheets("SheetName")
Dim wsStp As Worksheet
Set wsStp = wsStp.Worksheets("SheetName")
Dim wsDhl As Worksheet
Set wsDhl = wsDhl.Worksheets("SheetName")
'now work with those worksheets directly (no activate or select needed!)
wsStp.Range("B2").Formula = "=IF(SUMIF('Route Master.xls'!$C$7:$C$65536,$A2,'Route Master.xls'!$Q$7:$Q$65536)>0,TRUE,FALSE)"
wsStp.Range("B2").Copy
wsStp.Range(wsStp.Cells(2, 2), wsStp.Cells(EndRow2, 2)).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
' note this code does not work because `EndRow2` is nod defined
'select and activate a specific workbook/worksheet
'you do this ONLY if you want to focus it for the USER. Never do this for VBA instead work directly with the worksheets as shown above.
wbDhl.Activate
wsDhl.Select
Exit Sub
ERR_WB_OPEN:
MsgBox "One of the files could not be loaded.", vbCritical
End Sub
Don't forget to close your workbooks wbDhl.Close SaveChanges:=True/False otherwise they stay open.
See below. You can reference the workbook directly as pointed out by BigBen. In code, you never need to select ranges or activate workbooks/worksheets. You just need to reference them directly.
Notice I also added explicit declaration of types.
Dim a, b As Long
The line above will declare a as a variant and b as long
Sub Update_DHL()
Dim trk As Workbook, stp As Workbook, dhl As Workbook, wb As Workbook, wbNew As Workbook
Dim ws As Worksheet
Dim stpfile As String, DateStamp As String, strFolderpath As String
Dim EndRowTrk As Long, EndRowStp As Long, EndRowDHL As Long
Dim fileExplorer As FileDialog
Set dhl = [dhlfilePath]
Set trk = [truckfilePath]
Set stp = [stopfilePath]
stpfile = stp
Workbooks.Open Filename:=trk
Workbooks.Open Filename:=stp
Workbooks.Open Filename:=dhl
With Workbooks(stpfile).Worksheets(1)
.Range("B2").Formula = "Hi"
End With
End Sub

Resources