I have a workbook that the workbook formatting is changed regularly, however once changed (maybe weekly or monthly) then going forward until it is changed again a macro needs to replicate that format. Changing the VBA to account for the new formatting each time is very time consuming. Is it possible to format a workbook and then copy the formatting easily to VBA (after the fact not like a macro record) for future use?
In the past I have since used a hidden sheet within the workbook where the macro runs and I essentially copy/paste that into the sheet I am working with. This works but has the downside of when making changes I first need to copy data over to the "template" sheet to ensure everything is correctly aligned with new data.
Possibly some kind of macro that iterates through all cells of a range and outputs to the immediate window the VBA code needed to re-create the formatting?
Basically any ideas will help :)
There are so many formatting options that simply storing them as separate options will take far more space than just a duplicate template sheet. Just run the first code to update your template, and the second to copy it back:
option Explicit
Const TemplatesheetName = "mytemplate"
Sub CopyFormatting
dim ws as worksheet
dim source as worksheet
set source = activesheet
for each ws in worksheets
if ws.name = templatesheetname then
exit for
end if
next ws
if ws is nothing then
set ws = worksheets.add
ws.name = templatesheetname
end if
ws.usedrange.clearformats
source.usedrange.copy
ws.range("a1").pastespecial xlpasteformats
ws.visible = xlveryhidden
end sub
Sub BringBackFormats
dim ws as worksheet
for each ws in worksheets
if ws.name = templatesheetname then
exit for
end if
next ws
if ws is nothing then
msgbox "No template found",vbokonly,"Unabl;e to run"
else
ws.cells.copy
activesheet.range("a1").pastespecial xlpasteformats
end if
exit sub
(written on my phone, can't check the code, there may be typos)
Related
I am relatively new to VBA and this is my first post. I am puzzled by this issue I'm facing with what I believe should be very simple code. The goal is to automatically copy a range of Excel formulas on different sheets one at a time and paste them into a different range of cells on the same sheet (this range varies day to day as new data comes into our system, so I defined the range in excel formula in cells A3:D3, then VBA pulls the ranges in using the "indirect" function). For me this happens in my "For Each" loop
The macro runs just fine until this line, then I get a "Method PasteSpecial of Object 'Range' failed":
ws.Range("indirect($B$3)").PasteSpecial xlPasteAll
What's really strange is the entire Macro runs perfectly fine if I step through it with F8. As soon as I hit F5 or assign the macro to a button and try to run it all the way through? Error. Every time on the same step.
I hope its something simple and easy to fix, but thanks in advance for your help! If you need any further details from me to diagnose the issue, please let me know. Full macro is pasted below
gr8scotttch
Sub rearrangeformulas_refresh_1_2()
Dim ws As Worksheet
Dim wb As Workbook
Set wb = Workbooks("QueryMaster_Formulas.xlsm")
Set ws = wb.Sheets("Order_Data")
Application.Calculation = xlManual
For Each ws In wb.Sheets
ws.Select
Set ws = wb.ActiveSheet
ws.Range("$A$4").Select
ws.Range("indirect($A$3)").Copy
ws.Range("indirect($B$3)").PasteSpecial xlPasteFormulas
ws.Range("indirect($C$3)").Copy
ws.Range("indirect($D$3)").PasteSpecial xlPasteFormulas
ws.Range("$A$4").Select
Next ws
Set ws = wb.Sheets("Order_Data")
ws.Select
Application.Calculation = xlAutomatic
End Sub
(Sorry in advance for my poor English: not first Language :) )
I am writing a VBA Excel 2003 routine that runs through 50+ worksheets in a file, copies the worksheets (just as a temp copy) one by one and then performs actions on them before removing these temporary copies and returning the result of it's calculations on the worksheets content.
To be more precise: the code is called from an external file with a single (hidden) worksheet inside. When I open the file it runs a code to create a new toolbar in Excel, when I press a button on the toolbar, the code I have described above runs.
I know that not saving a file and performing many and many copies triggers this error, but now it is triggering at the first attempt (I have closed and reopened everything multiple times to be sure I am not keeping the not saved situation with me).
This is the code triggering the problem, I am sorry for poor formatting:
ActiveWorkbook.Worksheets("NAME OF THE FIRST WORKSHEET I WANT TO COPY").Copy ThisWorkbook.Worksheets("HiddenSheet")
Disclamer: the name of the worksheet is found by a For..Next cycle through the ActiveWorkbook.Worksheets array, but the code is not working even if i hard-code the name myself.
Here is a larger chunk of the code, to be clearer:
Set sourceWorkbook = ActiveWorkbook
For index = 1 To sourceWorkbook.Worksheets.Count
sourceWorkbook.Activate 'not sure if this is even needed
Set currWorksheet = sourceWorkbook.Worksheets(index)
currWorksheet.Copy ThisWorkbook.Worksheets("HiddenSheet")
Next index
The result is now consistently:
Run-time Error '1004'
Copy method of worksheet class failed.
I thank everybody in advance for the help!
Some useful guidelines:
Option Explicit
'Copy sheet
Sub CopySheet()
Dim ws1 As Workbook, ws2 As Workbook
'It's better to declare sheets and avoid activate
Set ws1 = Workbooks("Book1")
Set ws2 = Workbooks("Book2")
'Copy sheet "Test" from ws1(Book1) to ws2 (Book2) after all sheets
ws1.Worksheets("Test").Copy After:=ws2.Worksheets(Sheets.Count)
End Sub
Option Explicit
'Copy a range
Sub CopyRange()
Dim ws1 As Workbook, ws2 As Workbook
'It's better to declare sheets and avoid activate
Set ws1 = Workbooks("Book1")
Set ws2 = Workbooks("Book2")
'Copy from ws1(Book1), sheet "Test" & range A1:A5 to ws2 (Book2), sheet "sheet1" & range A1
ws1.Worksheets("Test").Range("A1:A5").Copy
ws2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
End Sub
I am using an excel Workbook for programtical generation. Once the workbook is created few of the sheets are having required data and few are blank with default templates only.
I need to delete all sheets having default templates (means no data). I can check specific cell to identify this however need to know how to check for all sheets and then delete sheets one by one.
I am having this piece of code:
Sub TestCellA1()
'Test if the value is cell D22 is blank/empty
If IsEmpty(Range("D22").Value) = True Then
MsgBox "Cell A1 is empty"
End If
End Sub
Try this:
Sub DeleteEmptySheets()
Dim i As Long, ws As Worksheet
' we don't want alerts about confirmation of deleting of worksheet
Application.DisplayAlerts = False
For i = Worksheets.Count To 1 Step -1
Set ws = Worksheets(i)
' check if cell D22 is empty
If IsEmpty(ws.Range("D22")) Then
Sheets(i).Delete
End If
Next
' turn alerts back on
Application.DisplayAlerts = True
End Sub
An alternative implementation using For-Each:
Sub deleteSheets()
Dim wb As Workbook
Dim sht As Worksheet
Set wb = Workbooks("Name of your Workbook")
'Set wb = ThisWorkbook You can use this if the code is in the workbook you want to work with
Application.DisplayAlerts = False 'skip the warning message, the sheets will be deleted without confirmation by the user.
For Each sht In wb.Worksheets
If IsEmpty(sht.Range("D22")) And wb.Worksheets.Count > 1 then
sht.Delete
End If
Next sht
Application.DisplayAlerts = True
End Sub
This mainly serves as a demonstration pf how you can easily loop through worksheets.
As suggested in the comments below by #Darren Bartrup-Cook , the logic according to which the sheets are deleted can and should be modified to not only suit your purposes but to also include safeguards.
Making sure there's always at least one worksheet in the workbook is one of them. This can be ensured in a multitude of ways. I updated my answer to implement one these.
Granted that I'm a newby.
I need to copy a specific cells area ("B6:C36") from a single worksheet (named "FILE MASTER") to all the other worksheets within the same workbook.
After that, I need to assign this brand new macro to a Button existing in the file master worksheet (therefore this macro has to have a name/sub otherwise I cannot assign it to a Button).
Having said that I tried to create a macro by using the recording feature of MS Excel, and it works. But it has a serious weakness: this automatedly encoding process has used/enunciated the name of every single worksheets in the source code. So if I add a new worksheet, this macro won't work correctly anymore.
Hope to have been enough clear
Thank you in advance to everybody.
You could change the code and try the below:
Option Explicit
Sub CopyYes()
Dim ws As Worksheet
With ThisWorkbook
'Copy the range
.Worksheets("FILE MASTER").Range("B6:C36").Copy
'Loop sheets
For Each ws In .Worksheets
With ws
'Avoid FILE MASTER
If .Name <> "FILE MASTER" Then
'Paste only values in A1 of each sheet
.Range("A1").PasteSpecial xlPasteValues
End If
End With
Next ws
End With
End Sub
Option Explicit
Sub CopyYes()
Dim ws As Worksheet
With ThisWorkbook
'Copy the range
.Worksheets("FILE MASTER").Range("B6:C36").Copy
'Loop sheets
For Each ws In .Worksheets
With ws
'Avoid FILE MASTER
If .Name <> "FILE MASTER" Then
'Paste values and formats in B6:C36 of each sheet
.Range("B6:C36").PasteSpecial xlPasteValues
.Range("B6:C36").PasteSpecial xlPasteFormats
End If
End With
Next ws
End With
End Sub
I am trying to create an Tracker. Need help with these ideas:
When the Excel book is opened, it must show only the "Tracker" Worksheet. All other sheets need to be hidden. Now am using the code {sheet.visible = xlveryhidden} But the code is too long, I have to include each sheet name. I need help with a code to show only the Tracker sheet but to hide all other sheets in the workbook.
I've included two comboboxes as year and month. Also included a Command button OK & Cancel. When clicked on OK, it has to verify the IF condition and show a specific sheet. I have no issues with that. it is showing a specific sheet. But I need a single line code to hide all other sheets
I have also included a "New Tracker" Command button. When Clicked on it, it must include a New sheet. Also too let the user to rename it. This worksheet must also be hidden once saved.
I aware the process is simple, but not sure how to complete it.
To hide all but the Tracker worksheet
Sub hidesheets()
Dim ws As Worksheet, wb As Workbook 'Create the variables we'll use for our worksheet and workbook objects.
Set wb = Excel.ActiveWorkbook 'Set the workbook variable to equal the active workbook. This can also be set to equal a named workbook if you want.
For Each ws In wb.Worksheets 'Loop through each worksheet in the workbook.
If Not ws.Name = "Tracker" Then 'If the worksheet's name isn't "Tracker" then...
ws.Visible = xlSheetVeryHidden 'Set it to very hidden.
Else 'If it is the "Tracker" worksheet, then ...
ws.Visible = xlSheetVisible 'Set it to visible.
End If 'End the IF/THEN statement.
Next ws 'Repeat for the next worksheet in the workbook.
End Sub
You'll have to modify this if you want it to work with a command button or do something with another worksheet. But it should get you started. I'd do it but I don't quite have the time right now.