using sheet index instead of name in VBA - 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

Related

How to loop through sheet and copy some specific range

So I would like my code to loop through sheets, depend on sheet name I would like to copy different range (if sheet will not be listed i want just to skip it) (lets say i know number/adress of the columns i would like to copy (number of rows might be different, depends on the orginal file i got) and i would like to copy all of these ranges one under another into sheet called check_data with additional column to the right saying from which sheet this part is comming from. I'm stuck sometimes this part of code works but it seems like it doesnt loop through the sheets.
So far i got this (but im totally new to vba)
Sub Copy_data()
Dim wb As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Set wb = ActiveWorkbook
Set ws1 = wb.Sheets("A")
Set ws2 = wb.Sheets("B")
Set ws3 = wb.Sheets("Check_data")
For Each ws In Worksheets
If ws.Name = "A" Then
ws1.Activate
ws1.Range("A1:Q1").Select
ws1.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ws3.Select
If ws3.Range("A1") = "" Then
ws3.Range("A1").Select
ActiveSheet.Paste
Else
Selection.End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste
End If
ElseIf ws.Name = "B" Then
ws2.Activate
ws2.Range("A1:Q1").Select
ws2.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ws3.Select
If ws3.Range("A1") = "" Then
ws3.Range("A1").Select
ActiveSheet.Paste
Else
Selection.End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste
End If
Else
End If
Next ws
End Sub
Thanks for any suggestions
A couple of things here. Always fully specify both the workbook and worksheets with objects, and preprend methods like Sheets with those objects, like this:
Dim wb As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb = ThisWorkbook
ws1 = wb.Sheets("A")
ws2 = wb.Sheets("Check_data")
ws1.Range("A1:Q1").Select
ws1.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
...and same thing when you are ready to paste, except that you need to explicitly activate the sheet that you are pasting into:
ws2.Activate
If ws2.Range("A1") = "" Then
ws2.Range("A1").Select
Selection.Paste
Else
Selection.End(xlDown).Offset(1, 0).Select
Selection.Paste
End If
Obviously, this isn't your entire code snippet rewritten, but it's the direction that you want to head in.

Macro to filter two criterion, copy, and delete | VBA

I'm VERY new to the world of VBA. My goal is to create a macro that will Filter out text "FL" and "CA" in column H, delete the row that contains them from the original raw data, and copy them to new individual workbooks. I was able to do this with one state, but when I go to add another I run into issues. Here is the code I have for Moving FL to another workbook:
Sub PMAPMoveFL()
'Rename sheet 1
ActiveSheet.Name = "Sheet1"
'Add new sheet and return to sheet 1
Sheets.Add After:=ActiveSheet
Sheets("Sheet1").Select
'Filter out FL, copy and paste to sheet 2
Selection.AutoFilter
ActiveSheet.Range("A1:A5000").AutoFilter Field:=8, Criteria1:="FL", Operator:=xlAnd
ActiveSheet.UsedRange.Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select
ActiveSheet.Paste
Rows("1:1").Select
Selection.Delete Shift:=xlUp
'Delete FL from sheet 1
Sheets("Sheet1").Select
Application.CutCopyMode = False
Selection.Delete
'Move FL sheet to new workbook
Sheets("Sheet2").Select
Sheets("Sheet2").Move
If Range("A1") = "" Then
MsgBox "This customer did not submit Florida data,you may delete this empty workbook"
End If
End Sub
It was tricky for me because the number of rows will never be absolute, but the column where the State is located is(Column H).
THANK YOU IN ADVANCE !!!
I'll try to clean up the code a little bit, and we'll work on giving you a dynamic range, as opposed to a fixed range in the process.
Dim LR as Long 'LR is Last Row
ActiveSheet.Name = "Sheet1"
With Sheets("Sheet1")
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Sheet2"
LR = .Cells(.Rows.Count,1).End(xlUp).Row
.Rows(1).AutoFilter
.Range("A1:A5000").AutoFilter Field:=8, Criteria1:="FL", Operator:=xlAnd
.Range("A1:K" & LR).SpecialCells(xlCellTypeVisible).Copy Sheets("Sheet2").Range("A1")
End With
With Sheets("Sheet2")
.Rows(1).Delete
.Move
If .Range("A1") = "" Then
MsgBox "This customer did not submit Florida data,you may delete this empty workbook"
End If
End With
I got rid of a few redundancies with this post. I also took out the deletion of Sheet1 data; I was unsure if you wanted the whole sheet removed or just the visible cells that show Florida results. Note that I arbitrarily used the last column as K, since it incorporates H within the A:K range.
I would guess that you want to store FL results somewhere else (another workbook) and keep the existing data, but I don't want to be wrong.
I would recommend the following code, in lieu of the above changes, which will copy Sheet1 to Sheet2, then perform separate actions on either, where Sheet1 deletes Florida Options and Sheet2 deletes non-Florida Options:
Dim i, k, LR as Integer
ActiveSheet.Name = "Sheet1"
With Sheets("Sheet1")
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Sheet2"
LR = .Cells(.Rows.Count,1).End(xlUp).Row
.Range("A1:K: & LR).Copy Sheets("Sheet2").Range("A1")
For i = 2 to LR
If .Cells(i,"H").Value="FL" Then
.Rows(i).Delete
End If
Next i
End With
With Sheets("Sheet2")
For k = 2 to LR
If .Cells(k,"H").Value="FL" Then
Else
.Rows(k).Delete
End If
Next k
End With
LR stays the same between the two sheets since the data is the same.

Excel Macro working different worksheet

Sub CopyPaste()
'
' CopyPaste Macro
'
' Keyboard Shortcut: Ctrl+Shift+P
'
Range("A2:C5").Select
Selection.Copy
Sheets("A").Select
Range("A2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Range("A6:C11").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("B").Select
Range("A2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Range("A12:C17").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("C").Select
Range("A2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Range("A18:C21").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("D").Select
Range("A2").Select
ActiveSheet.Paste
End Sub
I have trying making a Macro to do a basic task but I can't seem to figure it out, can anyone help please! I'm trying to create a macro that will copy data from one worksheet and place into another worksheet based on specific letter.
For example all "A" item will paste automatically into new worksheet name "A". This I can do with no problem. But, when I want to use the same macro with another row with different no of column is where I have my problem.
I already use recorded macro and then if the row from copy worksheet have been reduced, it will paste wrongly in new worksheet.
Is there any way to solve it?
thanks in advance.
P/S--> the new worksheet will have header in it. so it would be nice if they can paste start from A2 row. Can refer image below for example.
See Example / and see comment on the code
Option Explicit
Public Sub Example()
'Declare your Variables
Dim Sht As Worksheet
Dim rng As Range
Dim List As Collection
Dim varValue As Variant
Dim i As Long
With ThisWorkbook
'Set your Sheet name
Set Sht = ActiveWorkbook.Sheets("Sheet1")
'set your auto-filter, A1
With Sht.Range("A1")
.AutoFilter
End With
'Set your agent Column range # (1) that you want to filter it
Set rng = Range(Sht.AutoFilter.Range.Columns(1).Address)
'Create a new Collection Object
Set List = New Collection
'Fill Collection with Unique Values
On Error Resume Next
For i = 2 To rng.Rows.Count
List.Add rng.Cells(i, 1), CStr(rng.Cells(i, 1))
Next i
'Start looping in through the collection Values
For Each varValue In List
'Filter the Autofilter to macth the current Value
rng.AutoFilter Field:=1, Criteria1:=varValue
'Copy the AutoFiltered Range to new Workbook
Sht.AutoFilter.Range.Copy
Worksheets.Add.Paste
ActiveSheet.Name = Left(varValue, 30)
Next ' Loop back
'Go back to main Sheet and removed filters
Sht.AutoFilter.ShowAllData
Sht.Activate
End With
End Sub
Make sure to have header on your data, see below

Returning to starting worksheet

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.

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