VBA Excel - Generate New Workbook with macros from Old Workbook - vba

I currently have a workbook which contains a bunch of data on 2 of the sheets, which i use to construct a chart. Here's what it looks like:
So, In CRC I have a bunch of macros which pull through data from the Generator and MPNT and Construct the Chart in the CRC when a button on the MPNT is pressed.
MY ISSUE
For some reason, when I copy the CRC sheet out into a new worksheet using the function below, and then I use one of the buttons on the worksheet to hide/unhide data columns on the chart, it opens up the original file and uses the macros in that to run these buttons?
'''Extract Worksheet Button Function
Dim OriginalWB As Workbook, NewCRCWB As Workbook
Set OriginalWB = ThisWorkbook
Set NewCRCWB = Workbooks.Add
OriginalWB.Sheets("Generator").Copy Before:=NewCRCWB.Sheets("Sheet1")
OriginalWB.Sheets("Module Part Number Tracker").Copy Before:=NewCRCWB.Sheets("Generator")
OriginalWB.Sheets("CRC").Copy Before:=NewCRCWB.Sheets("Module Part Number Tracker")
Application.DisplayAlerts = False
NewCRCWB.Worksheets("Generator").Visible = False
NewCRCWB.Worksheets("Module Part Number Tracker").Visible = False
NewCRCWB.Worksheets("Sheet1").Delete
NewCRCWB.Activate
Application.DisplayAlerts = True
End Sub
MY AIM
To get around this I need to develop a function which will create a new workbook, and do all of the generation straight into that workbook and transfer the macros into there, however I'm not sure how to do this hence
MY QUESTION
How do I:
Open a New Workbook
Run the macros from CRC in current
workbook onto a CRC sheet on the newly opened workbook
In the process ensure that all the macros are copied through to the CRC
sheet in the New Workbook
Thanks!!

Related

Disable alert when manually deleting a sheet

Is there a way in VBA to disable the alert that pops up when MANUALLY deleting a sheet (right click sheet and delete)? I have seen Application.DisplayAlerts = False, however this seems to only work for me when deleting a sheet using VBA (Sheets("Sheet1").delete). I am trying to disable the alert for the whole workbook when you manually right click on a sheet and click delete. Thanks.
In case anyone else is looking for the same scenario:
...eliminate the need to confirm deleting a sheet when presenting the
workbook in meetings. While going through the sheets I often double
click on pivot tables to view detail, and I would like to eliminate
the pop-up alert when I delete the generated sheet...
If new sheets are generated only when double-clicking a pivot table, this might be a suitable solution
Placed in ThisWorkbook, the code bellow will delete any new sheets, when selecting a different sheet
Option Explicit
'Place this code in ThisWorkbook module
'Expects that all new sheets are generated by double-clicking a pivot table
Private pivotWs As Worksheet
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Set pivotWs = Sh
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If Not pivotWs Is Nothing Then
If Sh.Name = pivotWs.Name Then
Application.DisplayAlerts = False
pivotWs.Delete
Set pivotWs = Nothing
Application.DisplayAlerts = True
End If
End If
End Sub

Excel VBA - How to use worksheet event in add-in module?

I am new to Excel Add-ins and I am not sure how to write mi programm.
I would like to put in an add-in a code so that, when the workbook that uses the add-in is opened, it creates a sheet named "mainSheet".
I can use the event handler in the Workbook, but is it possible to put the code in the module of the add-in and still be able to run it?
I found this on the "Automate Excel" web site. Hope this helps
The following code works opening a workbook. It automatically adds a new sheet and labels it with the name. It also checks to see that the sheet doesn’t already exist – to allow for the possibility of it being opened more than once a day.
This code makes use of the Workbook Open Event and must be placed in the workbook module under the “Open work Book” event. The function Sheet_Exists must be placed in a module and this checks whether or not the sheet exists:
Private Sub Workbook_Open()
Dim New_Sheet_Name As String
New_Sheet_Name = "mainSheet"
If Sheet_Exists(New_Sheet_Name) = False Then
With Workbook
Worksheets.Add().Name = New_Sheet_Name
End With
End If
End Sub
==
Function Sheet_Exists(WorkSheet_Name As String) As Boolean
Dim Work_sheet As Worksheet
Sheet_Exists = False
For Each Work_sheet In ThisWorkbook.Worksheets
If Work_sheet.Name = WorkSheet_Name Then
Sheet_Exists = True
End If
Next
End Function

How to replace a sheet using VBA ?

I'd like to copy a sheet from a workbook and paste it in the 2nd sheet in my active workbook. I'm new with vba, it doesn't seem difficult but my code doesn't work. The sheet, which is copied, is opened in a new workbook and not in my active workbook.
Thanks for your help !
My code :
Sub copyPaste()
Dim classeur1 As Excel.Workbook
Dim classeur2 As Excel.Workbook
Set classeur1 = Workbooks.Open("Macintosh HD:Users:LouiseDhainaut:Documents:Stage:test_modifiable.xlsx")
Set classeur2 = ThisWorkbook
classeur1.Sheets(1).Copy
classeur1.Sheets(1).Paste Destination:=ThisWorkbook.Sheets(2).Range("A1")
classeur2.Save
classeur1.Close
End Sub
Try:
classeur1.Sheets(1).Copy Before:=ThisWorkbook.Sheets(2)
Instead of the
classeur1.Sheets(1).Copy
classeur1.Sheets(1).Paste Destination:=ThisWorkbook.Sheets(2).Range("A1")
Although note that copying an entire worksheet will copy the entire worksheet, not just the contents of it.
If you are looking to copy only the contents, you will need a different code, for example:
classeur1.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets(2).Range("A1")

Call and run a code in another sheet

I have a button on sheet 1 that will run code code a created sheet, basically the program creates a new sheet, copy the code on the sheet 2 to this new sheet, run the code on this new sheet, display the final result on sheet 1 and delete this new sheet. But I having problems to run the code, is not running the code.
The new sheet has the name Calcs.
Private Sub CommandButton2_Click()
Dim MySheet As Worksheet
Set MySheet = ThisWorkbook.Sheets("Calcs")
Call MySheet.Mycode
End Sub
Mysheet does not contain any code when you are calling it.
If you are deleting the new sheet, you really have no purpose in storing the code in the new sheet. Why don't you store the code as public in a module?

Updating target workbook - extracting data from source workbook

My question is as follows:
I have given a workbook to multiple people. They have this workbook in a folder of their choice. The workbook name is the same for all people, but folder locations vary.
Let's assume the common file name is MyData-1.xls.
Now I have updated the workbook and want to give it to these people. However when they receive the new one (let's call it MyData-2.xls) I want specific parts of their data pulled from their file (MyData-1) and automatically put into the new one provided (MyData-2).
The columns and cells to be copied/imported are identical for both workbooks. Let's assume I want to import cell data (values only) from MyData-1.xls, Sheet 1, cells B8 through C25 ... to ... the same location in the MyData-2.xls workbook. How can I specify in code (possibly attached to a macro driven import data now button) that I want this data brought into this new workbook. I have tried it at my own location by opening the two workbooks and using the copy/paste-special with links process. It works really well, but It seems to create a hard link between the two physical workbooks. I changed the name of the source workbook and it still worked. This makes me believe that there is a "hard link" between the tow and that this will not allow me to give the target (MyData-2.xls) workbook to others and have it find their source workbook.
To clarify my understanding, each user has a spreadsheet called MyData-1.xls but with varying locations. You would like to send each person a new spreadsheet MyData-2 which will automatically pull in data from range B8:C25 in MyData-1.xls?
There are various options on doing this and below I have provided one way of doing this. In short, the user will open MyData-2, click a button, and the code will search for MyData-1 on their directory, open the workbook, grab the data, paste it into MyData-2, and then close MyData-1.
Sub UpdateWorkbook()
'Identify workbook you would like to pull data from (same for all users)
Dim TargetWorkbook As String
TargetWorkbook = "MyData-1"
'Get the full path of that workbook by searching in a specified directory
Dim TargetPathName As String
TargetPathName = GetFilePath(TargetWorkbook)
'Retrieve data in range B8:C25, copy and paste, then close workbook
Dim TargetRng As Range
Application.ScreenUpdating = False
Workbooks.Open Filename:=TargetPathName
Set TargetRng = Sheets("Sheet1").Range("B8:C25")
TargetRng.Copy Destination:=ThisWorkbook.Worksheets(1).Range("B8:C25")
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub
Function GetFilePath(TargetWkbook As String) As String
Dim FullFilePath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error Resume Next
With Application.FileSearch
.NewSearch
.LookIn = "C:\"
.FileType = msoFileTypeExcelWorkbooks
.SearchSubFolders = True
.Filename = TargetWkbook
If .Execute > 0 Then
FullFilePath = .FoundFiles(1)
End If
End With
GetFilePath = FullFilePath
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Function
By way of explanation:
In the sub you first need to specify the name of the workbook MyData-1
The Function GetFilePath will then get the full path name of the workbbok. Note that I have set it to look in the "C:\" drive and you may want to amend that
Once we have the full file path we can easily open the workbook and copy the required range.
Note that the screenupdating is turned off to create the 'illusion' that the workbook has not been opened when the data is copied. Also, I have added a button on the worksheet of MyData-2 to trigger the code i.e. user opens workbook, presses button, and data is imported.
Finally, this code could be augmented significantly and you may want to tweak it. For example, error checking if file not found, searching in multiple directories (e.g C:\, D:)...
Hope this gets you started on the right track
You should use the copy/paste-special for values only:
Private Sub ImportData_Click()
On Error GoTo OpenTheSheet
Workbooks("MyData-1.xls").Activate
GoTo SheetOpen
OpenTheSheet:
Workbooks.Open "MyData-1.xls"
Workbooks("MyData-1.xls").Activate
SheetOpen:
On Error GoTo 0
Workbooks("MyData-1.xls").Worksheets("sheetwhatever").firstRange.Copy
Workbooks("MyData-2.xls").Worksheets("anothersheet").yourRange.PasteSpecial(xlPasteValues)
End Sub
This could be cleaned up a bit, but it's always messy to do file stuff in VBA, I'd probably put the opening code in a function.
Make sure they put the new file in the same directory as the old file.