VBA, Loop through sheets not detecting parameters? - excel

So I'm trying to format to all sheets apart from the "Names" sheet. and what I came up with below doesn't seem to be able to loop and detect the sheet "Names". It will try to format "Names" the said sheet is active or it will only apply format a single other sheets when the sheets is active
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Names" Then
Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$Q$19").AutoFilter Field:=4, Criteria1:="="
Rows("2:2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
ActiveSheet.Range("$A$1:$Q$16").AutoFilter Field:=4
Columns("G:G").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete Shift:=xlToLeft
Range("J15").Select
End If
Next ws
I've tried rewriting the codes completely but the same problem persists

In addition to removing Activesheet, rewriting to avoid .select, and maybe considering an alternative to Criteria1:="=" (as already mentioned);
Consider using a With statement to definitely connect each action to the current sheet.
Sub Format_Worksheets()
Dim WS As Worksheet
Dim lRow As Long
Dim lCol As Long
For Each WS In ThisWorkbook.Worksheets
If WS.Name <> "Names" Then
With WS
.Rows("1:1").AutoFilter
.Range("$A$1:$Q$19").AutoFilter Field:=4, Criteria1:="="
lRow = .Range("A2").End(xlDown).Row
lCol = .Range("A2").End(xlToRight).Column
.Range(.Cells(lRow, 1), .Cells(lRow, lCol)).Delete shift:=xlUp
.Range("$A$1:$Q$16").AutoFilter Field:=4
lCol = .Range("G1").End(xlToRight).Column
.Range("G1", .Cells(1, lCol)).Delete shift:=xlToLeft
End With
End If
Next WS
End Sub
Let me know if this works out for you. It did for me... but I'm not 100% sure the formatting will match what your did. I rewrote it without .select or .activate but sometimes it's hard to tell without looking at the data.

Related

Concatenate sheet name with values in cell range

I am trying to write a macro that removes unnecessary columns and copies/ pastes data from one column next to another. I then want it to take the worksheet name (which is variable) and concatenate it with the values in a static range of cells, but only after the columns have been modified.
The macro runs without error until the concatenate step.
Is there a better way to write this or what am I doing incorrectly? The error is "Object variable or With block not set". The error occurs at "Set rngTemp = ws.Range("A21", "H21")" line.
Thank you in advance for your consideration.
Sheets("Channel-0").Select
Range("F21:F62").Select
Selection.Delete Shift:=xlToLeft
Range("G21:H62").Select
Selection.Delete Shift:=xlToLeft
Range("H21:L62").Select
Selection.Delete Shift:=xlToLeft
Columns("G:G").Select
Range("G11").Activate
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("E21:E62").Select
Selection.Copy
ActiveWindow.SmallScroll Down:=-39
Range("G21").Select
ActiveSheet.Paste
Range("G19").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
Dim ws As Worksheet
Dim rngCell, rngTemp As Range
Set rngTemp = ws.Range("A21", "H21")
For Each cell In rngTemp
cell.Value = ActiveSheet.Name & cell.Value
Next cell
End Sub

How do I make the cell Range work in VBA?

I have a problem with the autofill function. I want to use the macro to fill in the date until there is nothing left in B. The problem is that there are some gaps there. Can I change the code so that it fills up to the last line in B. I tried it with the code below. However, it does not work.
Sub fill()
Sheets("Table1").Select
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Range("C2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""",R[-1]C,RC[-1])"
ActiveCell.Select
Dim last As Long
Range("C2").Select
Range(Selection, Selection.End(xlToRight)).AutoFill Destination:=Range("C2:C" & last)
Selection.End(xlDown).Select
Selection.ClearContents
ActiveCell.Offset(-1, 0).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Copy
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("C:C").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("A1").Select
End Sub
You do not need such a lengthy process. You can do it in just couple of lines. For example
rng.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Here is an example. Assuming that your range is from C2 onwards as shown below.
Try this code
Option Explicit
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Table")
Dim lRow As Long
With ws
lRow = .Range("C" & .Rows.Count).End(xlUp).Row
Dim rng As Range
Set rng = .Range("C3:C" & lRow)
Dim visibleCells As Range
On Error Resume Next
Set visibleCells = rng.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not visibleCells Is Nothing Then
visibleCells.FormulaR1C1 = "=R[-1]C"
End If
End With
End Sub
In Action
Worth a Mention
Also avoid using Select/Selection/Activecell etc. You may want to read up on How to avoid using Select in Excel VBA
You do not need VBA to achieve what you want. You can achieve the same using few clicks.
NON VBA Method
Select your range. In this case C3:C13
Press CTRL + G to bring up the Go To dialog box
Click Special button
Select the Blanks radio button and click OK.
In the Formula bar type =C2 and press CTRL + ENTER key and you are done
In Action

Excel VBA copy-paste from source workbook to multiple-sheet workbook

I have a source workbook with one sheet from which, after applying some filters, I copy-paste ranges of data into a new workbook with 2 sheets.
After copy-pasting I shift and remove some columns around in the newly created sheets. The code below works fine until pasting the values selected into the 2nd sheet. However, when I wish to make the modifications to this 2nd sheet, they are done to the first sheet instead which messes up all my data.
After searching for hours I cannot figure out why the second sheet is not addressed properly so I'd be grateful for any help with this issue.
Sub ActiveHeadcount()
Dim ActiveHC As Workbook
Dim HCrange As Range
Dim ActiveHCrangedest As Range
Dim lastrow As Integer
Dim getbook As String
With ActiveSheet.UsedRange
.Value = .Value
End With
With Sheet1
.Range("A1:AR1").AutoFilter
.Range("A1:AR1").AutoFilter Field:=8, Criteria1:="Active"
.Range("$A$1:$AR$1").AutoFilter Field:=10, Criteria1:=Array( _
"Apprenticeship", "Fixed term contract", "Permanent",_
"Permanent-Expat","Trainee","="), Operator:=xlFilterValues
End With
Set ActiveHC = Workbooks.Add
Set HCrange = ThisWorkbook.Worksheets_
("Sheet1").Cells.SpecialCells(xlCellTypeVisible)
HCrange.Copy (ActiveHC.Worksheets("Sheet1").Range("A1"))
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("AL:AL").Select
Selection.Cut
Range("B1").Select
ActiveSheet.Paste
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Columns("K:K").Select
Selection.Delete Shift:=xlToLeft
Columns("M:R").Select
Selection.Delete Shift:=xlToLeft
Columns("Q:Q").Select
Selection.Delete Shift:=xlToLeft
Columns("Y:AC").Select
Selection.Delete Shift:=xlToLeft
Columns("AB:AC").Select
Selection.Delete Shift:=xlToLeft
Sheets("Sheet1").Name = "SAP HC " & Format(Date, "ddmmyy")
If ActiveSheet.FilterMode Then
Cells.AutoFilter
End If
With Sheet1
.Range("A1:AR1").AutoFilter
.Range("$A$1:$AR$1").AutoFilter Field:=8, Criteria1:=Array( _
"Active", "Inactive"), Operator:=xlFilterValues
.Range("$A$1:$AR$1").AutoFilter Field:=10, Criteria1:=Array( _
"Contractor", "Subcontractor"), Operator:=xlFilterValues
End With
Set HCrange = ThisWorkbook.Worksheets_
("Sheet1").Cells.SpecialCells(xlCellTypeVisible)
HCrange.Copy (ActiveHC.Worksheets("Sheet2").Range("A1"))
The changes below happen in Sheet1 instead of Sheet2 where I want then:
Columns("B:B").Select
Selection.Delete Shift:=xlToLeft
Columns("AJ:AJ").Select
Selection.Cut
Columns("B:B").Select
Selection.Insert Shift:=xlToRight
The code below works and saves the file with the proper sheet names:
Sheets("Sheet2").Name = "Contractors " & Format(Date, "ddmmyy")
ActiveHC.SaveAs Filename:="D:\Macro Finance HC" & "\Global Headcount " _
&Format(Date, "ddmmyy") & ".xlsx"
End Sub
Changes
Reference set to the new worksheet
Code to select and copy combine to single operation
Filter extracted to it's own sub routine
Sub ActiveHeadcount()
Dim ActiveHC As Workbook
Dim HCWorksheet As Worksheet
Dim HCrange As Range
Dim ActiveHCrangedest As Range
Dim lastrow As Integer
Dim getbook As String
With ActiveSheet.UsedRange
.value = .value
End With
FilterSheet1 Array("Active", "Inactive"), Array("Apprenticeship", "Fixed term contract", "Permanent", "Permanent-Expat", "Trainee", "=")
Application.SheetsInNewWorkbook = 1
Set ActiveHC = Workbooks.Add
Application.SheetsInNewWorkbook = 3
Set HCWorksheet = ActiveHC.Worksheets(1)
Set HCrange = ThisWorkbook.Worksheets _
("Sheet1").Cells.SpecialCells(xlCellTypeVisible)
HCrange.Copy HCWorksheet.Range("A1")
With HCWorksheet
.Columns("B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Columns("AL").Copy .Columns("B")
.Columns("AL").Delete
.Columns("C").Delete Shift:=xlToLeft
.Columns("K").Delete Shift:=xlToLeft
.Columns("M:R").Delete Shift:=xlToLeft
.Columns("Q").Delete Shift:=xlToLeft
.Columns("Y:AC").Delete Shift:=xlToLeft
.Columns("AB:AC").Delete Shift:=xlToLeft
.Name = "SAP HC " & Format(Date, "ddmmyy")
End With
If ActiveSheet.FilterMode Then
Cells.AutoFilter
End If
FilterSheet1 Array("Active", "Inactive"), Array("Contractor", "Subcontractor")
Set HCrange = ThisWorkbook.Worksheets _
("Sheet1").Cells.SpecialCells(xlCellTypeVisible)
HCrange.Copy (ActiveHC.Worksheets("Sheet2").Range("A1"))
End Sub
Sub FilterSheet1(arFilter1, arFilter2)
With Sheet1
.Range("A1:AR1").AutoFilter
.Range("$A$1:$AR$1").AutoFilter Field:=8, Criteria1:=Array( _
"Active", "Inactive"), Operator:=xlFilterValues
.Range("$A$1:$AR$1").AutoFilter Field:=10, Criteria1:=arFilter2, Operator:=xlFilterValues
End With
End Sub

how to create macro in a file in an excel changing dates

I'm creating a report everyday and the data needed are:
Open file #1 with file name: file1\today_23012015 for today.
In file #1 i need to get the items with yesterday's date which is 22012015 and copy those and paste it to the new workbook1.
Open file #2 with file name: file2\today_23012015 for today.
In file #2 I need to get the items with yesterday's date which is 22012015 and copy and paste to the sheet 2 of workbook1.
Can anyone help me create macro to this?
Sub Macro17()
'
' Macro17 Macro
'
'
Workbooks.Open Filename:="C:\Users\estillor\Desktop\file1240115.xlsx"
Windows("With macro.xlsm").Activate
Windows("file1240115.xlsx").Activate
ActiveCell.Offset(-8, -11).Range("A1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$D$24").AutoFilter Field:=4, Operator:= _
xlFilterValues, Criteria2:=Array(2, "1/23/2015")
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("With macro.xlsm").Activate
Sheets("Sheet1").Select
ActiveSheet.Paste
Windows("file1240115.xlsx").Activate
Windows("With macro.xlsm").Activate
Workbooks.Open Filename:="C:\Users\estillor\Desktop\file2240115.xlsx"
ActiveCell.Offset(-4, -16).Range("A1").Select
Application.CutCopyMode = False
Selection.AutoFilter
ActiveSheet.Range("$A$1:$D$10").AutoFilter Field:=4, Operator:= _
xlFilterValues, Criteria2:=Array(2, "1/23/2015")
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("With macro.xlsm").Activate
Sheets("Sheet2").Select
ActiveSheet.Paste
End Sub
This will be a process to get this working completely,
Practice with this code, adjust the folder locations and file names.
Once you get this to work for you, post back with a more detailed question.
Sub Do_Something_Cool()
Dim wb As Workbook, ws As Worksheet
Dim Bk As Workbook, sh As Worksheet
Dim dirt As String
Dim FnM As String
Dim FileNm As String
Dim Rws As Long, Rng As Range
dirt = "C:\Users\Dave\Downloads\"'adjust location
FnM = "file1240115.xlsx"
FileNm = dirt & FnM
Application.ScreenUpdating = 0
Set wb = Workbooks("WithMacro.xlsm")
Set ws = wb.Sheets("Sheet1")
Set Bk = Workbooks.Open(FileNm)
Set sh = Bk.Worksheets(1)
With sh
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
.Range("A1").AutoFilter Field:=4, Criteria1:="=1/23/2015"
Set Rng = .Range(.Cells(2, "A"), .Cells(Rws, "D")).SpecialCells(xlCellTypeVisible)
Rng.Copy Destination:=ws.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
.AutoFilterMode = 0
Bk.Close True
End With
End Sub

Subscript Out of Range in Macro

Here is my code:
Workbooks("A").Worksheets("Sheet1").Activate
Range("B2:BG2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.copy
Workbooks("C.xlsm").Worksheets("Sheet1").Activate
ActiveSheet.Paste
I am getting a Subscript Out of Range error at the first line.
Now error is at last line:
Workbooks("A.xlsm").Activate
Worksheets("Sheet1").Select
Range("B2:BG2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.copy
Workbooks("C.xlsm").Worksheets("Sheet1").Activate
ActiveSheet.Paste
ActiveWindow.SmallScroll Down:=45
lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
Range("B" & lMaxRows + 1).Select
Workbooks("AB.xlsm").Activate
Worksheets("Sheet1").Select
Range("B2:BG2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.copy
Workbooks("C.xlsm").Worksheets("Sheet1").Activate
ActiveSheet.Paste
Rather than syntax like:
Workbooks("A").Worksheets("Sheet1").Activate
use something like:
Workbooks("A.xlsm").Activate
Worksheets("Sheet1").Select
Try setting reference for workbook and worksheet first:
Dim wb1 As Workbook
Dim ws1 As Worksheet
Dim wb2 As Workbook
Dim ws2 As Worksheet
Set wb1 = Workbooks("Book1")
Set ws1 = wb1.Sheets(1)
Windows(2).Activate
Set wb2 = ActiveWorkbook
Set ws2 = wb2.Sheets(1)
ws1.Activate
ws1.Range("B2:BG2").Select
Selection.Copy
wb2.Activate
ws2.Activate
ActiveSheet.Paste
To answer your second question.
Try replacing :
Workbooks("C.xlsm").Worksheets("Sheet1").Activate
with :
Workbooks("C.xlsm").Activate
Worksheets("Sheet1").Activate
The reason behind this is: when you call it in one line, you only want to activate the worksheet within that workbook; rather than activating both the workbook and the worksheet.
Another reason that may be causing trouble in this case is if you do not have a valid region selected in your Workbooks("C.xlsm").Worksheets("Sheet1") when you try to copy into it. Try adding Cells(1,1).Select before pasting.
I'll end with a better alternative that does not require activating workbooks/worksheets :
The .Copy method has a "destination" parameter that may be set to be within any existing sheet of any open workbook. For example, you could replace the last 4 lines with something like :
Range(Selection, Selection.End(xlDown)).Copy _
(Workbooks("C.xlsm").Worksheets("Sheet1").Range("A1"))

Resources