Is it possible to copy data from a cell into a macro? - vba

I have written data in a cell that is updated by a macro - it appends a reference depending on what somebody has called a new sheet.
In Cell A1 I end up with macro code that is updated with the new sheet name. Currently users have to copy this text and open another macro and paste the code in, however they keep doing it wrong and breaking it.
What I would like to do is write a macro to copy the contents of Cell A1 and paste them into the original macro.
If it possible to do this?

Based on a suggestion at the MrExcel.com forum:
Sub aaa()
For i = 1 To Application.VBE.CodePanes.Count
Application.VBE.CodePanes(i).CodeModule.ReplaceLine 1, "alert('Yo') ' New code"
Next i

I know this is not an answer to your question but I'm just offering some information. I would suggest that you don't have users create a macro in each sheet. You can access anything on any sheet from a module. I am not sure what you whole process is but you could think of it more along the lines of looking for the sheets you want to change.
Public sub ProcessSheets()
Dim ws As Excel.Worksheet
Dim iIndex As Integer
'Loop through all the worksheets in the workbook.
For iIndex = 1 To ActiveWorkbook.Worksheets.count
'Activate the current sheet, if you need to.
Set ws = Worksheets(iIndex)
ws.Activate
'Check the name of the worksheet.
If Left(ws.Name, 2) = "HD" or Left(ws.Name, 2) = "ER" Then
'Call the function that changes the worksheet here.
'Maybe feed it the worksheet name.
UpdateWorksheet ws.Name
End if
Next iIndex
End Sub

Related

VBA. Create new workbooks using another workbook as a template and naming each new workbook from a list

I have a workbook that I need to create 150 copies of. I have the list of what I want to save each new workbook as in cells A1 to A150 in another workbook.
I've looked around but I can't find any code that does what I need. If it makes it easier, I could put the list into the template workbook, but would need to delete that sheet from each new workbook before saving and closing it.
This code should help you:
Sub Sample()
Dim wsToCopy As Worksheet, wsNew As Worksheet
With Sheets("Sheet1")
LastRow = Sheets("Sheet1").Cells(.Rows.Count, 1).End(xlUp).Row
For a = 1 To LastRow
Set wsToCopy = ThisWorkbook.Sheets("TemplateSheet")
Set wsNew = ThisWorkbook.Sheets.Add
wsNew.Name = Sheets("Sheet1").Cells(a, 1).Value
wsToCopy.Cells.Copy wsNew.Cells
Next
End With
End Sub
Explaining:
At a sheet named "Sheet1", you need to have a list of the to-create sheets names, starting at the first row, always in the first column.
The macro will create a new sheet, rename-it and copy everything from the sheet "TemplateSheet". And then, will pass to the next Sheet1's row.
So basically, just name your template sheet as "TemplateSheet" and add the 150 names at the first row of "Sheet1".
You can delete the template and the Sheet1 later.

Dynamic reference of Sheets from a cell - VBA

I'm not sure if this is possible, but it's the one thing I haven't found answered accross the web.
I created one template workbook Schedule.xls that will be filled out by different people, say personA, personB and personC. I need to extract the same range from each workbook by copying it and pasting it into a master file Master.xls, so that I can get the information from each person into this masterbook.
This Master.xls will have as much sheets as persons filling Schedule.xls.
For example, let's stay with those 3 persons: personA, personB and personC.
Once they generate their schedule, I want to get that information and copy it into Master.xls, but in separate sheets named personA, personB and personC.
I want to do this by setting a cell in Schedule.xls, say A1, where people can choose a value between personA, personB and personC.
This way I can create a dynamic reference for the sheet in Master.xls. in which the macro will paste the info.
`Range("B2.D5").Select
Selection.Copy
Workbooks.Open Filename:= _
"C:\My Documents\Master.xlsx"
Sheets(*REFERENCE*).Select
Range("B2").Select
ActiveSheet.Paste
Range("A1").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWorkbook.Close`
What should I write instead of REFERENCE to set the sheet I want to write on?
Thanks in advance.
I'll suggest a simple, no-code approach. Then, I'll give you some VBA code for your specific request.
Place two workbooks, Carl's SlaveWB.xlsx and your Master.slxm, in the same folder for simplicity. Open the worksheet you want to sync (1-way copy) in both spreadsheets. Create these sheets manually for this simple example. Now, click in cell A1 in the master sheet. While in edit mode, type "=" then click in cell A1 in Carl's worksheet (in the other workbook). Your sheets are now linked. You can do this not just for A1 but the entire worksheet -- just copy/paste cell A1 to the entire worksheet. Now, Carl can take his workboook on the road. Here is how he check's in. He simply copies his latest workbook into your predesignated folder. When you open your master workbook, it will automatically pull in all the data from Carl's "checked-in" workbook.
If you prefer to copy from one workbook to another (to capture formatting), it is not difficult.
First, rename or delete the old "Carl" worksheet in master. Here is code for deleting a worksheet by name. If the name of the sheet in the master is stored in Carl's "Sheet1" worksheet, cell A1, you can pass this as the value of WSName: Workbooks("SlaveWB").Sheets("Sheet1").Cells(1,1).Value.
'DeleteWorksheet(WSName)
Public Function DeleteWorksheet(WSName As String)
'If Not IIf(IsNull(DebugMode), False, DebugMode) Then On Error GoTo FoundError
If Not Range("DebugMode").Value Then On Error Resume Next
Dim WorksheetExists As Boolean
DeleteWorksheet = False
'if no worksheet name provided, abort
If Len(WSName) < 1 Then Exit Function
'if worksheet exists, delete
WorksheetExists = False
On Error Resume Next
WorksheetExists = (Sheets(WSName).Name <> "") 'if worksheet exists, set WorksheetExists = True
On Error GoTo FoundError
If WorksheetExists Then Sheets(WSName).Delete 'if worksheet exists, delete
DeleteWorksheet = True 'function succeeded (deleted worksheet if it existed)
Exit Function
FoundError:
On Error Resume Next
DeleteWorksheet = False
Debug.Print "Error: DeleteWorksheet(" & WSName & ") failed to delete worksheet. "
End Function
Next, copy the revised worksheet from Carl's workbook to the master. The code below copies a worksheet from srcWBName to tgtWBName and names the sheet whatever you like in tgtWBName. I reocmmend you keep the code only only in the master spreadsheet. It is too risky to put the same code in every copy held by every user. And, it will be hard to manage code updates.
Sub CopyWSBetweenWBs(srcWBName As String, srcWSName As String, _
tgtWBName As String, tgtWSName As String)
'srcWBName - name of PersonA's workbook
'srcWSName - name of worksheet to copy from Person A's workbook
'tgtWBName - target workbook, the master
'tgtWSName - what you want to call the worksheet after copying it to the target/master.
' If you want this sheetname to be taken from a cell, just pass the cell
' reference. For example, this can be
' Workbooks(srcWBName).Sheets(srcWSName).Cells(1,1).Value
Dim srcWB As Workbook
Dim srcWS As Worksheet
Dim tgtWB As Workbook
Dim tgtWS As Worksheet
'Create XL objects
Set srcWB = Workbooks(srcWBName)
Set srcWS = srcWB.Worksheets(srcWSName)
Set tgtWB = Workbooks(tgtWBName)
Set tgtWS = tgtWB.Worksheets(tgtWSName)
' Start at the source
srcWB.Activate
srcWS.Activate
' Copy to target workbook
srcWS.Copy Before:=tgtWB.Sheets(1) '<~~ copy to beginning of workbook
' After copying the worksheet, it is active, so you can rename it now.
ActiveSheet.Name = tgtWSName
End Sub
That's it. I hope this helps.

Excel VBA to Work Across Workbooks

I am very new to VBA coding and don't have very good understanding of what I am doing to be honest. But here I go.
I am looking to see if:
Can VBA codes have dyname values? So instead of the code saying execute on a set sheet (e.g "Sheet1") that value changes depending a value in a certain cell.
To trigger a VBA on another workbook. For example I want to run a VBA from Workbook A that triggers a VBA on Workbook B.
To fully explain I want to open Workbook A (and Workbook B if needed, it doesn't matter) and click a button that runs a VBA on Workbook B but on a certain Sheet depending on the value of a cell in Excel A (if the cell says "sheet3" the VBA runs on "sheet3" on Workbook B). I also want cells in Workbook A to reference cells in Workbook B but the the sheet name to by dynamic. For example I have pasted the basic cell reference bellow but instead of having Sheet1 I want it to change depending on the value in a cell.
='[Workbook B.xlsx]Sheet1'!$A$4
I know this sounds very complicates and confusing, but if I could get any help that would be greatly appreciated.
Sub ReportStepOne()
Dim myRow As Long
myRow = 4
Rows(myRow).Value = Rows(myRow).Value
Dim rng As Range
Set rng = Range("A4:AC200")
rng.Cut rng.Offset(1, 0)
Range("A1:AC1").Copy Range("A4:AC4")
End Sub
I want to:
edit this code to make it fire on a certain sheet
make it so the sheet name is referenced to whatever is in cell A o Sheet2 in Report.xlsm.
Run a macro in Report.xlsm that runs the above script (which is called "StepOne" in a file called "Historical Data.xlsm"
The code below takes the value of cell A4 on sheet2 in Reports.xlsm and sets the ws variable to the sheet in Historical data.xlsm which is then used for the rest of the code. If possible I'd advise against having your subs spread out over multiple projects but that is just my opinion. I think it is easier to use proper referencing like below.
Since you want a button trigger on the Report.xlsm I'd suggest moving this code to that workbook. If properly referenced it you can open, edit, save and close any workbook from a single project which again, in my opinion is easier than calling subs in a different project.
Sub ReportStepOne()
Dim wbHis As Workbook, wbRep As Workbook
Dim strWsName As String
Dim ws As Worksheet
Set wbHis = Workbooks("Historical data.xlsm")
Set wbRep = Workbooks("Reports.xlsm")
strWsName = wbRep.Worksheets("Sheet2").Cells(4, 1)
Set ws = wbHis.Worksheets(strWsName)
With ws
With .Rows(4)
.Value = .Value
End With
With .Range("A4:AC200")
.Cut .Offset(1, 0)
End With
.Range("A1:AC1").Copy .Range("A4:AC4")
End With
End Sub
To trigger a VBA on another workbook
Option Explicit
Sub RunVBA()
Dim xlApp As Excel.Application
Dim xlWorkBook As Workbook
Set xlApp = New Excel.Application
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\Om3r\Desktop\Book1.xlsm")
xlApp.Visible = True
xlWorkBook.Application.Run "Module1.SubName" ' Modulename.Subname
End Sub
To reference worksheet use
Sub CopyRange()
'// From sheet1 to sheet2
Worksheets(2).Range("A1").Value = Worksheets(1).Range("A1").Value
End Sub

Creating an Archive Macro Excel VBA

In this latest project the desire is to have a button & macro that will do the following:
When clicked the macro will copy all the data from the existing workbook & save it to another location. To create the copy of the workbook I will be using the following code below:
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Data.xlsm"
Application.DisplayAlerts = True
This code was sourced from - http://goo.gl/t7qOyB
Once the copy has been archived, the data in the existing workbook must then be removed leaving all the formatting behind. How can removing the data but keeping the formatting be achieved?
Use the .ClearContents() property of Cells Collection
Sub ClearAll()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Cells.ClearContents
Next
End Sub
This code iterates through all sheets in the current workbook and deletes the values from cells keeping the formatting.
Update!
If you wanted to clear only specific range on each sheet then
Sub ClearAll()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Range("A1:B20").ClearContents
Next
End Sub
This will clear only range A1:B20 on each sheet.

Copy an entire worksheet to a new worksheet in Excel 2010

I have found similar questions that deal with copying an entire worksheet in one workbook and pasting it to another workbook, but I am interested in simply copying an entire worksheet and pasting it to a new worksheet -- in the same workbook.
I'm in the process of converting a 2003 .xls file to 2010 .xlsm and the old method used for copying and pasting between worksheets doesn't paste with the correct row heights. My initial workaround was to loop through each row and grab the row heights from the worksheet I am copying from, then loop through and insert those values for the row heights in the worksheet I am pasting to, but the problem with this approach is that the sheet contains buttons which generate new rows which changes the row numbering and the format of the sheet is such that all rows cannot just be one width.
What I would really like to be able to do is just simply copy the entire worksheet and paste it. Here is the code from the 2003 version:
ThisWorkbook.Worksheets("Master").Cells.Copy
newWorksheet.Paste
I'm surprised that converting to .xlsm is causing this to break now. Any suggestions or ideas would be great.
It is simpler just to run an exact copy like below to put the copy in as the last sheet
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub
ThisWorkbook.Worksheets("Master").Sheet1.Cells.Copy _
Destination:=newWorksheet.Cells
The above will copy the cells. If you really want to duplicate the entire sheet, then I'd go with #brettdj's answer.
' Assume that the code name the worksheet is Sheet1
' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)
' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"
I really liked #brettdj's code, but then I found that when I added additional code to edit the copy, it overwrote my original sheet instead. I've tweaked his answer so that further code pointed at ws1 will affect the new sheet rather than the original.
Sub Test()
Dim ws1 as Worksheet
ThisWorkbook.Worksheets("Master").Copy
Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub
'Make the excel file that runs the software the active workbook
ThisWorkbook.Activate
'The first sheet used as a temporary place to hold the data
ThisWorkbook.Worksheets(1).Cells.Copy
'Create a new Excel workbook
Dim NewCaseFile As Workbook
Dim strFileName As String
Set NewCaseFile = Workbooks.Add
With NewCaseFile
Sheets(1).Select
Cells(1, 1).Select
End With
ActiveSheet.Paste
If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by #/jean-fran%c3%a7ois-corbett and #thanos-a in combination with simple VBA as shown below.
Sub sbInsertWorksheetAfter()
'This adds a new visible worksheet after the last visible worksheet
ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created
ThisWorkbook.Sheets("Master").Cells.Copy _
Destination:=ActiveSheet.Cells
'This gives the the new ActiveSheet a default name
With ActiveSheet
.Name = Sheet12.Name & " copied"
End With
'This changes the name of the ActiveSheet to the user's preference
Dim sheetname As String
With ActiveSheet
sheetname = InputBox("Enter name of this Worksheet")
.Name = sheetname
End With
End Sub