Returning to starting worksheet - vba

I've recorded a quick macro which moves from my starting worksheet to a different worksheet, copies some cells and then goes back to the original worksheet to paste the contents of the copied cells.
While recording the macro the worksheet had a certain name and I'm trying to understand how to change it so that the macro will return to whatever worksheet I was on when initiating the macro and not returning to a specifically named macro.
This is what the code looks like:
Sheets("vlookup template").Select
Range("A1:K1").Select
Selection.Copy
Sheets("Sheet8").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("vlookup template").Select
Range("B2:K2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet8").Select
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.AutoFill Destination:=Range("B2:K11")
Range("B2:K11").Select
Selection.Copy
I want to change it so that instead of going to 'sheet8' it returns to the original sheet.

Dim homeSheet As WorkSheet
Set homeSheet = ActiveSheet
'.... Do stuff
homeSheet.Activate
Please see Avoid Select and Activate for more information.

Related

using sheet index instead of name in VBA

I would like to copy some contents from my first sheet, paste them into a new sheet, then delete the first sheet and rename the new (only) sheet to Sheet1. But I never know what the second sheet will be named when I create it. Most of the time, it will be Sheet2, but I can't count on it. Here is the code taken just from creating a macro that does it, but it is using the sheet names as they were created in this instance. I want to use the index of the sheets instead but don't know the syntax:
Columns("A:D").Select
Selection.Copy
Sheets("Sheet2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Application.CutCopyMode = False
ActiveWindow.SelectedSheets.Delete
Sheets("Sheet2").Select
Sheets("Sheet2").Name = "Sheet1"
So where is says "Sheet2"...how do I make that so it's using the second sheet, not necessarily the sheet named Sheet2?
Thanks.
Worksheets(2) is the way to refer to the second sheet.
Worksheets(Worksheets.Count) to the last one.
Try it like this:
Debug.Print Worksheets(Worksheets.Count).name
you can create a variable that will be the new sheet:
Sub sheetdelet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Worksheets.Add
.Worksheets("Sheet1").Range("A:D").Copy ws.Range("A1")
Application.DisplayAlerts = False
.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
ws.Name = "Sheet1"
End With
End Sub

VBA Paste Data After Last Row Issue

I am compiling data from multiple worksheets to place on one consolidated sheet. The first sheet is easy because I can paste the entire sheet however after that it becomes tricky as I only need from A5-H### as I no longer need the header. I then need to paste this information at the bottom of the previous paste. I am getting a Range of Object "_Global" failed for the 'Range(lastRow).Select'. The issue is when I look at it in the debugger it is coming up with the correct row number. What am I doing wrong?
Sheets(1).Select
Cells.Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Consolidation Sheet").Select
Range("A1").Select
ActiveSheet.Paste
Sheets(2).Select
Range("A5:A925").Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Consolidation Sheet").Select
Range("A5").Select
lastRow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row + 1
Range(lastRow).Select
ActiveSheet.Paste
You need your Range statement in the following form (for example):
Range("A1").Select
So since you've got the row number (lastRow), you just need to add the column reference too:
Range("E" & lastRow).Select
Extra info
Avoid using Select by referring directly to the worksheets/ ranges you want to deal with
Sheets(1).Cells.Copy Destination:=Sheets("Consolidation Sheet").Range("A1")
With Sheets(2)
.Range(.Range("A5:A925"),.Range("A5:A925").End(xlToRight)).Copy
End With
With Sheets("Consolidation Sheet")
.Cells(.Rows.Count, "E").End(xlUp).Offset(1,0).PasteSpecial
End With

Copy and paste values from a workbook into a closed workbook

I'm fairly new to VBA coding, so please pardon any ignorance.
How can I copy from one sheet (DIC) in workbook 1 and paste values in a sheet (Archive) in a second workbook starting from the first empty row? I don't have the second worksheet open often, so if it can be done without keeping it open, that would be preferred.
I compiled a code to get it to copy into a second sheet within the same workbook, but I'm stumped when it comes to getting it into the second workbook.
Here's the code that I have so far:
Sub copytoarchive()
'Copy From DIC
Sheets("DIC").Select
Range("A4:Q4").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste into Archive
Sheets("Archive").Select
Dim NextRow As Range
Set NextRow = Range("A65536").End(xlUp).Offset(1, 0)
NextRow.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Clear Memory
Set NextRow = Nothing
End Sub
avoid all that Select/Selection an refer to fully qualified ranges
try this (commented) code:
Option Explicit
Sub copytoarchive()
Dim destSht As Worksheet
Workbooks.Open ("C:\...\FileToCopyTo.xlsx") '<- at opening a workbook it becomes the active one
Set destSht = ActiveWorkbook.Worksheets("Archive") '<-- set the destination worksheet in the activeworkbook
With ThisWorkbook.Worksheets("DIC") '<--refer to your source worksheet in the workbook this macro resides in
With .Range(.Range("A4:Q4"), .Range("A4:Q4").End(xlDown)) '<--| refer to your range whose values are to be copied
destSht.Cells(destSht.Rows.Count, 1).End(xlUp).Offset(1).Resize(.Rows.Count, .Columns.Count).Value = .Value '<--| copy values in a equally sized range in destination worksheet starting at the first empty cell in column "A"
End With
End With
destSht.Parent.Close True '<--| close the destination workbook, which is obtained as the Parent object of the destination worksheet
End Sub
just change "C:...\FileToCopyTo.xlsx" with your actual destination workbook full path
be aware that such a range as you selected may incur in an error should there be no filled rows below "A4:B4"
You can certainly copy a range from a closed workbook.
http://www.rondebruin.nl/win/s3/win024.htm
I don't believe you can save data to a closed workbook. I can't even imagine how that would work.

VBA Excel Copy Data from specific worksheet to a specific worksheet in another workbook

I need to write a MACRO which copies a table from a specific worksheet, to a specific worksheet (Sheet 3) in a master workbook, in the first empty row.
Ideally I would like to have the MACRO apply to all files in a specific folder. Pulling from different workbooks have a worksheet named "Sheet 3". ("Sheet 3" is just a placeholder)
This is what I have so far:
Sub Master()
Application.ScreenUpdating = False
Dim erow
Workbooks.Open Filename:= "C:\Example\File.xlsx"
Sheets("Sheet 3").Select
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveWorkbook.Close
Workbooks("MASTER").Sheets("Sheet 3").Activate
'MASTER is the name of the Master Workbook
erow = Sheets("Sheet 3").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Selection.Paste
'This is where the MACRO gives a "Run-time error '438': Object doesn't support
'this property or method"
Application.ScreenUpdating = True
End Sub
Any help would be appreciated!

How to prevent excel macro from pasting empty rows

I am trying design a macro in excel 2007. Here is what I need it to do:
When I enter an ID into a specific cell and run the macro, it will search for that ID in column A of a different workbook and autofilter. Then I need it to copy that data and paste it into the first workbook. My code is working, however when it is pasting a ton of extra rows beneath my data. How can I make it only copy and paste data and not empty rows? Here is my code:
Sub Medications()
'
' Medications Macro
'
' Keyboard Shortcut: Ctrl+m
'
Range("B1").Select
Workbooks.Open Filename:= _
"I:\Pharmacy\MTMP\2013\Master Lists\CMR Medication List.xlsx"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Member ID"
Range("A1").Select
Selection.AutoFilter
ActiveSheet.Range(Selection, ActiveCell.SpecialCells(xlLastCell)).AutoFilter Field:=1, Criteria1:=Workbooks("Standardized Format Spreadsheet.xlsm").Worksheets("Demographics").Range("B1").Value
Cells.Select
Selection.Copy
Windows("Standardized Format Spreadsheet.xlsm").Activate
Sheets("Detailed Medication List").Select
Range("A1").Select
ActiveSheet.Paste
Windows("CMR Medication List.xlsx").Activate
Application.CutCopyMode = False
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Sheets("Demographics").Select
End Sub
It is always best to avoid selecting items whenever possible. You can use set a workbook to an object and access it through that.
The reason you are getting extra cells when you copy/paste is because you are selecting every cell and then copying. I suggest using only the used range so you don't pick up any extra cells.
Sub Medications()
Dim CMR_Wkbk As Workbook
Dim SFS_Wkbk As Workbook
Set SFS_Wkbk = Workbooks("Standardized Format Spreadsheet")
Set CMR_Wkbk = Workbooks.Open("I:\Pharmacy\MTMP\2013\Master Lists\CMR Medication List.xlsx")
Range("A1").Value = "Member ID"
ActiveSheet.UsedRange.AutoFilter Field:=1, Criteria1:=SFS_Wkbk.Sheets("Demographics").Range("B1").Value
ActiveSheet.UsedRange.Copy Destination:=SFS_Wkbk.Sheets("Detailed Medication List").Range("A1")
Application.DisplayAlerts = False
CMR_Wkbk.Close
Application.DisplayAlerts = True
Sheets("Demographics").Select
End Sub
Cells.Select
Selection.Copy
Cells.Select is selecting the entire content of the worksheet. I don't know, obviously, what you sheet looks like, but try selecting only the CurrentRegion - the equivalent of what is highlighted when you click in a cell and press Ctrl-A:
ActiveCell.CurrentRegion.Copy