VBA Copy a Worksheet to a New Sheet without Formulas - excel

I am trying to copy whatever selected sheet (notwithstanding the name of the sheet) within the same workbook. First, I have tried the code of copying and renaming a new sheet (with formulas) that I found elsewhere. It is working well:
Public Sub CopySheetAndRename()
Dim newName As String
On Error Resume Next
newName = InputBox("Enter the name for the copied worksheet")
If newName <> "" Then
ActiveSheet.Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = newName
End If
End Sub
However, I would just like to have the newly created sheet without formulas. I tried to add the lines like: ActiveSheet.PasteSpecial Paste:=xlPasteValues
but it is not working at all. I have read also this post Copy Excel sheet to another excel book without formulas without any result.
Thank you for your help!
Stanley

Related

VBA issues with merged workbook

I am trying to create a template automating tasks for a user that is not very familiar with Excel. To start, it grabs the files from a folder on the users desktop (OneDrive connection if that matters), merges them into new sheets of the template and renames the sheets to the appropriate names. Second, it should copy the used range of each sheet and paste it into tables (connected to pivots and graphs).
The problem I'm having is that after the merge, but before the paste into tables, I need to insert some calculated columns. When I try to insert the formula and copy it down using the macro, it pastes up. As in, if I place the formula in H2, it copies up to H1 instead of the used rows range.
Funny thing is the code works perfectly on the original workbook, but not after the merge. There may be a better way to merge them, but I haven't found it. Any help is appreciated!
Here is my code:
To merge the workbooks-
Sub Combine_Workbooks()
'Combines all the workbooks in folder named FLEET DATA DUMP on desktop of user.
Dim Path As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
'Update this to username
Path = "C:\Users\hsthompson\OneDrive - Quanta Services Management Partnership, L.P\Desktop\FLEET DATA DUMP\"
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Sheets("CODE").Activate
Application.ScreenUpdating = True
End Sub
To Rename Sheets (Separated due to issues with object issues)
Sub Rename_Sheets()
'Renames sheets to link to pivot tables.
Sheets("Sheet1").Name = "DLH"
Sheets("RentalEquipmentAnalysis_Assigne").Name = "Rentals"
Sheets("Report_AssetDetailExport - 2023").Name = "Assets"
End Sub
To alter the sheet named Rentals to use column H as a calculated column
Sub Rentals()
Dim UsedRws As Long
UsedRws = Cells(Rows.Count, "A").End(xlUp).End(xlUp).Row
Sheets("Rentals").Range("H2:H" & UsedRws).FormulaLocal = "=TODAY()-WEEKDAY(TODAY())"
MsgBox UsedRws
Sheets("Rentals").Range("H1") = "Week Ending"
End Sub
I have tried updating the code to several different variations:
Range vs Cells
Double .End(xlUp)
Tried xlDown, but that pasted the formula down to the bottom of the sheet 104000
Tried copying and pasting manually into the workbook and the code worked fine.
Formula vs FormulaLocal
Etc

How do you refer to a list of sheets in VBA?

I am extremely new to VBA and recorded a macro but I would like to update the recorded macro to have it dynamically work with multiple sheets as sheet names are currently hard coded.
For example,
Sub FormattingFinal()
Sheets("Template Format").Select
Range("A6:G8").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Hamilton").Select
Range("A6").Select
ActiveSheet.Paste
End Sub
I would like "Template Format" to be hard coded as I always want to copy from this sheet, but change "Hamilton" to loop through a list of sheets that I specify (all sheets in the workbook except for two sheets). How do I go about doing this?
Sub FormattingFinal()
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
'change Exclude1 and 2 to the sheets you want
If sh.Name <> "Exclude1" And sh.Name <> "Exclude2" Then
'The first argument to Copy is the destination, so you can do it all in one line
ThisWorkbook.Worksheets("Template Format").Range("A6:G8").Copy sh.Range("A6:G8")
End If
Next sh
End Sub

VBA Add second Sheet with same Name

I have a CommandButton which opens a UserForm and create a copied Sheet with the name of the ComboBox Value.
This is My Code:
Private Sub CommandButton1_Click()
[UserForm1].Show ' Open UserForm
End Sub
Private Sub CommandButton2_Click()
Dim ws As Worksheet
ActiveWorkbook.Sheets("Sheet1").Visible = True ' Unhide Sheet
Sheets("Sheet1").Copy _
Before:=ActiveWorkbook.Sheets("Sheet1") ' Copy Sheet
Set ws = ActiveSheet
ws.Name = ComboBox1.Value ' Name Sheet
[UserForm1].Hide ' Close UserForm
ActiveWorkbook.Sheets("Sheet1").Visible = False ' Hide Sheet again
End sub
Now my problem is, if there are two machines with name "Machine Type 1" Excel gets an Error. So what do i have to change in my code, that the second sheet would named e.g. "Machine Type 1 (2)?
Thanks for your help.
you could try this
Private Sub CommandButton1_Click()
If IsSheetThere(ComboBox1.Value) Then 'if some sheet with chosen name already there
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
With ActiveSheet 'reference just copied sheet
.UsedRange.Clear 'clear its content
Sheets("Sheet1").UsedRange.Copy ActiveSheet.Range("A1") ' copy Sheet1 content and paste into it
End With
Else 'otherwise
Sheets("Sheet1").Copy Before:=Sheets(Sheets.Count) ' make a copy of "Sheet1" sheet
ActiveSheet.Name = ComboBox1.Value 'and rename it as per chosen name
End If
Me.Hide
End Sub
Function IsSheetThere(shtName As String) As Boolean
On Error Resume Next
IsSheetThere = Not Sheets(shtName) Is Nothing
End Function
the code line:
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
is the one that leaves Excel the burden of somehow "counting" the number of already existing sheets with the chosen name, and name the new one appropriately
You can use the following sub which calls the below function, just apply the same logic using .Copy
Sub create_new_sheet_with_name(name As String, wb As Workbook, aftersheet As Variant)
Dim i As Integer
i = 2
If sheet_name_exists(name, wb) Then
Do While sheet_name_exists(name & " (" & i & ")", wb)
i = i + 1
Loop
wb.Sheets.Add(after:=aftersheet).name = name & " (" & i & ")"
Else
wb.Sheets.Add(after:=aftersheet).name = name
End If
End Sub
Function sheet_name_exists(name As String, wb As Workbook) As Boolean
For Each sheet In wb.Worksheets
If sheet.name = name Then
sheet_name_exists = True
Exit Function
End If
Next sheet
sheet_name_exists = False
End Function
here's an example of how to use the sub:
Sub test()
create_new_sheet_with_name "hi", ThisWorkbook, ThisWorkbook.Sheets(1)
'this adds a new sheet named "hi" to thisworkbook after thisworkbook.sheets(1)
End Sub
Technically this isn't an answer to this question... but it's better because it will help you solve this and many other coding tasks on your own.
There is a simple way to create VBA code for most basic tasks.
If there's something Excel can do that you want to be able to do programmatically, just Record a Macro of yourself performing the action(s), and then look at the code that Excel generated.
I have a terrible memory, I can't remember commands I used yesterday. So it's not only quicker and less frustrating for others for me to figure it out myself, but the more often I do that, the quicker I'll learn (without asking others to do the thinking for me on a basic question).
I fact, I'm guess that the majority of veteran VBA coders learned at least partly by analyzing recorded macros. I know I did.

Paste data from another workbook excel vba, error: Paste method of Worksheet class failed

I'm trying to copy a set of data from a workbook to another workbook, let's say I'm going to copy data from Book A to Book B. First, I go to Book A copy the list, then go to Book B to run below copydata macro(I want to paste the data onto the new sheet before go back to the previous sheet in Book B.)
Sub copydata()
Dim lstviewpg As String
lstviewpg = ActiveSheet.Name
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "newsheet"
Sheets("newsheet").Activate
ActiveSheet.Paste
Sheets(lstviewpg).Activate
End Sub
The macro failed at line 6 due to Paste method of Worksheet class failed. Anyone got any idea how to fix it?
ActiveSheet.Paste
Paste method of Worksheet class failed error will also be produced if there is nothing on the clipboard i.e. clipboard is empty.
So to confirm that clipboard is not empty, right click in any cell on the sheet and if the Paste is greyed out that means the clipboard is empty.
You have to use PasteSpecial()
Moreover you can simplify a little:
Sub copydata()
Dim lstviewpg As String
lstviewpg = ActiveSheet.Name
With Sheets.Add(After:=Sheets(Sheets.Count)) '<--| add a new sheet and reference it
.Name = "newsheet" '<--| set the name of referenced sheet
.PasteSpecial '<--| paste data
End With
Sheets(lstviewpg).Activate
End Sub

csv output from excel error but other data types work correctly?

Ok I am attempting to write a Macro that saves an excel Workbook into a csv file. I have tried many different solutions but I am still having issues getting the values to print properly. when I open the file it produces. The rest of the code I left out all it does is takes the original spreadsheet and copys the contents into a temporary sheet so I can take multiple sheets from the same WB and print them to the same csv file. it also has a module that will clear all formatting and contents of that temporary file. I ran the code to just print it to a new excel spreadsheet and it worked fine just will not print to a csv not sure why
out put looks like this:
K ! bîh^ [Content_Types].xml ¢(
[… skip a bunch of binary lines …]
KÆ8k¡~¥-ÙÔäá ûÜ
My code looks like this:
Sub SaveFile()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Raw Data Copy")).copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = "test"
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.path & "\" & NewName & ".csv"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
SaveCopyAs only saves an Excel Workbook in Excel format. Even if you append .csv to your filename, the file is still an .xls formatted file.
The Workbook SaveAs method lets you to specify the type of file you want to save to.
However, if you use the SaveAs method, it changes the name of your current file.
This earlier question on Stack Overflow has some options on how to use the SaveAs method without changing the name of the file you are working on.
Why does VBA ActiveWorkbook.SaveAs change the open spreadsheet? has some comments on how to properly use the SaveAs method and not have the name of your current file changed in the process.

Resources