How to replace a sheet using VBA ? - 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")

Related

Excel VBA macro to copy certain columns to another Workbook

I need to copy certain columns of one spreadsheet to another spreadsheet.
In order to do so, I have a macro:
Sub Submit()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn =
Workbooks("Submission_Form.xlsm").Worksheets("RGSheet").Columns("A")
Set myData = Workbooks.Open("I:\Projects\...\Macros\RG.csv")
Worksheets(1).Select
Worksheets(1).Range("A1").Select
Set targetColumn = Workbooks("RG.csv").Worksheets(1).Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
However, when the cursor hits targetColumn, it gives error:
Run-time error '9':
Subscript out of range
For the sake of simplicity, I have put RG.csv in the same folder as Submission_Form.xlsm. So I am really confused why is it giving error.
I would also like to know how to handle if the RG.csv is located in another directory.
The error is probably because Submission_Form.xlsm isn't opened(?). Your code looks a little inconsistent. Maybe just open both source and destination, and copy the column. Something like this?
Option Explicit
Sub Submit()
Dim vSourceWorkbook As Workbook
Dim vDestinationWorkbook As Workbook
Set vSourceWorkbook = Workbooks.Open("Submission_Form.xlsm")
Set vDestinationWorkbook = Workbooks.Open("I:\Projects\...\Macros\RG.csv")
vSourceWorkbook.Worksheets("RGSheet").Range("A:A").Copy Destination:=vDestinationWorkbook.Worksheets(1).Range("A:A")
End Sub

VBA Excel - Generate New Workbook with macros from Old Workbook

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!!

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?

Store COPY of a worksheet in worksheet variable

What I want to achieve:
I want to assign copy of a worksheet to variable, for later use.
What I tried and results
First : The code below works fine. Something like this I would like to achieve, but using worksheet.copy.
Sub DuplicateSheetRenameFirst()
Dim wsDuplicate As Worksheet
Set wsDuplicate = Worksheets.Add
wsDuplicate.Name = "Duplicate"
End Sub
Second : Using the copy method, creates a worksheet in current workbook, but generates a Runtime error 424 - Object required.
Sub DuplicateSheetRenameSecond()
Dim wsDuplicate As Worksheet
Set wsDuplicate = Worksheets("Sheet1").Copy(after:=Worksheets(Worksheets.Count))
'above line : runtime error 424 object required, but the sheet is created
wsDuplicate.Name = "Duplicate"
End Sub
Third : Creates a worksheet in new workbook (so creates book, then sheet), but still generates the same Runtime error 424 - Object required.
Sub DuplicateSheetRenameThird()
Dim wsDuplicate As Worksheet
Set wsDuplicate = Worksheets("Sheet1").Copy
'above line : runtime error 424 object required, but the sheet is created in new workbook
wsDuplicate.Name = "Duplicate"
End Sub
Workaround : I can modify any of the second or third way to at first copy the sheet and then set the variable to activesheet, but I was wandering if there is a one step way of doing this. I'm not sure if this would work all the time, since the activesheet may not be the one just copied, maybe.
The Question:
Is there a simple (one step) way to store the copy of a worksheet in a variable? Preferably without errors or without filtering the error with error handler.
This is maybe ok?
Sub copySheet()
Dim ws As Excel.Worksheet
Excel.ThisWorkbook.Sheets("Sheet1").Copy After:=Sheets(1)
Set ws = Excel.ThisWorkbook.ActiveSheet
End Sub
It is unfortunate that in this case you need to use an Active... object. Generally it is good practice to avoid Active... objects.
You cannot do this though as the method .copy is not returning an object of the worksheet class:
Sub copySheet()
Dim ws As Excel.Worksheet
Set ws = Excel.ThisWorkbook.Sheets("Sheet1").Copy(After:=Sheets(1))
End Sub
Some further explanation is in this previous post:
Why does Worksheet.Copy not return a reference to the new workbook created
In MSDN it is not altogether obvious that the method returns nothing:
https://msdn.microsoft.com/EN-US/library/office/ff837784.aspx
...but in your friend Excel's Object Explorer it is more obvious. If it returned a worksheet object then by the arrow would read:
Sub Copy([Before], [After]) as Worksheet

Excel VBA Can't access sheet on external workbook

I have created a custom function in Excel using VBA. I'm trying to get data from a different workbook using the Workbooks.Open(path) command. Here's my code:
Option Explicit
Function TestFunction() As String
mySub
TestFunction = "Success."
End Function
Sub mySub()
Dim path As String
Dim wk As Workbook
path = "C:\Users\jg\Desktop\machine_data.xlsm"
Set wk = Workbooks.Open(path)
Dim ws As Worksheet
Set ws = wk.Sheets(1)
Debug.Print ws.Range("A2")
End Sub
Sub Test()
Debug.Print (TestFunction())
End Sub
Now my problem is the following:
When I run the Sub Test() within the VBA environment from Excel everything works as planned. machine_data.xlsm gets opened and the field A2 shows up in debug.
Once I go to the workbook where I defined this module in and type =TestFunction() into a cell, I get a #VALUE!. The file also doesn't get opened.
If I comment these two lines:
Set ws = wk.Sheets(1)
Debug.Print ws.Range("A2")
the cell will show Success!, but the file still doesn't open.
What am I doing wrong? Both workbooks are .xlsm files. I am using Microsoft Office Excel 2007.
Just throw everything from mySub into the test function and if everything is successful have test function return the value of the cell. So testFunc = ws.Range("A2").
As DaveU already stated UDFs can only return values. I found a different workaround simply calling the function from within the VBA environment which lets me modify cell contents wherever I'd like.