Delete Row of only visible cells - excel

I have a macro that compiles data from another worksheet and then manipulates said data. My first step is filtering by blanks and deleting all of the rows that appear. I thought I wrote the code correctly but I'm not apparently not, because each time I get a Run-time error '1004': Application-define or object-defined error
I don't see anything wrong with my variables, the column I'm filtering by is column D.
If you can see anything in my code that would help I'd love to know. Thank you!
Sub X50()
Dim wb As Workbook
Dim ws As Worksheet, macro As Worksheet, Pscrub As Worksheet
Dim lastRow As Long
Dim mlastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("X50 - All")
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
Sheets.Add After:=Sheets(Sheets.Count), Count:=2
Sheets(3).Select
Sheets(3).Name = "Pre Scrub"
Sheets(4).Select
Sheets(4).Name = "Macro"
Set Pscrub = wb.Sheets("Pre Scrub")
Set macro = wb.Sheets("Macro")
mlastRow = macro.Range("A" & Rows.Count).End(xlUp).Row
ws.Range("AM6:AM" & lastRow).Copy Destination:=macro.Range("A1")
ws.Range("AL6:AL" & lastRow).Copy Destination:=macro.Range("B1")
ws.Range("F6:F" & lastRow).Copy Destination:=macro.Range("C1")
ws.Range("E6:E" & lastRow).Copy Destination:=macro.Range("D1")
ws.Range("G6:G" & lastRow).Copy Destination:=macro.Range("E1")
ws.Range("K6:K" & lastRow).Copy Destination:=macro.Range("F1")
macro.Range("A1").AutoFilter Field:=4, Criteria1:=(""), _
Operator:=xlFilterValues
macro.Range("D2:D" & mlastRow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
macro.AutoFilterMode = False
wsPrescrub.Range("$A$1:$F$" & mlastRow).RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6) _
, Header:=xlYes
End Sub

Related

Select multiple ranges with VBA

I need to select multiple ranges in a worksheet to run various VBA code on them. The ranges will always begin on row 84 but the end depends on how far down the data goes. I've been selecting these ranges separately using code like this:
Sub SelectRange()
Dim LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A84:B" & LastRow).Select
End Sub
That works fine, but I can't figure out how to select multiple ranges at once. I've tried everything I can think of:
Range("A84:B", "D84:E", "H84:J" & LastRow).Select
Range("A84:B,D84:E,H84:J" & LastRow).Select
Range("A84:B & LastRow,D84:E & LastRow,H84:J & LastRow").Select
Nothing works. I get a run-time error when running any of those.
Use UNION:
Dim rng as Range
With ActiveSheet
set rng = Union(.Range("A84:B" & LastRow),.Range("D84:E" & LastRow),.Range("H84:J" & LastRow))
End With
rng.select
But if you intend on doing something with that range then skip the .Select and just do what is wanted, ie rng.copy
Put your dis-continued range address in the first argument of Range object.
For example, Range("A:A,D:D").Select will select column A and column D.
In your case, you may try:
Dim str As String, LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
str = "A84:B" & LastRow & ",D84:E" & LastRow & ",H84:J" & LastRow
Range(str).Select
Range("A84:B & LastRow & "," & "D84:E & LastRow & "," & "H84:J & LastRow").Select

Why doesn't my paste special work properly?

When I run the code below, my range, Master, pastes twice, once with content, and once with empty cells.
Sub AddProj() 'Adds new template to Data Worksheet
Sheet1.Range("Master").Copy
Sheet1.Range("C" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlFormats
FindProj
End Sub
When my code is like below, it works properly but doesn't paste formatting:
Sub AddProj() 'Adds new template to Data Worksheet
Sheet1.Range("Master").Copy Sheet1.Range("C" & Rows.Count).End(xlUp).Offset(1)
FindProj
End Sub
FindProj is just some function to copy and paste a cell:
Sub FindProj() 'Finds project name in Historical Worksheet and pastes it in Data Worksheet
Dim Lastrow As Long
Dim Newproj As Long
Dim Master As Range
Dim Masterrow As Long
Masterrow = Worksheets("Data").Range("Master").Rows.Count
Lastrow = Sheets("Historical").Cells(Rows.Count, "B").End(xlUp).Row
Newproj = Sheets("Data").Cells(Rows.Count, "C").End(xlUp).Row
Sheets("Historical").Cells(Lastrow, "B").Copy Sheets("Data").Cells(Newproj - Masterrow + 1, "C")
End Sub
Also, the first code only works once and then never again.
Obviously the PasteSpecial is messing things up but I can't see why. Is there a way to incorporate PasteSpecial into the second code?
Will this help?
Sheet1.Range("Master").Copy
With Sheet1.Range("C" & Rows.Count).End(xlUp).Offset(1)
.PasteSpecial xlPasteFormats
.PasteSpecial xlPasteValues
End With

How to Paste a Range onto another worksheet with filters on

This seems like a simple task but I keep running into various errors. I need to filter worksheet B and then copy a column of data. I then need to filter worksheet A and then paste the copied data into a column.
Worksheets("SheetB").Select
lastRowOne = Range("B" & Rows.Count).End(xlUp).Row
Range("DL2:DL" & lastRowOne).AutoFilter Field:=116, Criteria1:="<>Apples"
lastRowTwo = Range("B" & Rows.Count).End(xlUp).Row
Range("DG2:DG" & lastRowTwo).AutoFilter Field:=111, Criteria1:=Target
'Target is already defined earlier in the Macro and functions fine
lastRowThree = Range("B" & Rows.Count).End(xlUp).Row
Range("DX2:DX" & lastRowThree).Copy
Worksheets("SheetA").Activate
lastRowFour = Range("B" & Rows.Count).End(xlUp).Row
Range("A2:A" & lastRowFour).AutoFilter Field:=1, Criteria1:=Target
lastRowFive = Range("B" & Rows.Count).End(xlUp).Row
Range("Z2:Z" & lastRowFive).SpecialCells(xlCellTypeVisible).Select
Selection.PasteSpecial Paste:=xlPasteRange, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
In place of the last line I have also tried:
ActiveSheet.Paste
The first returns a "Run-time error '1004':
PasteSpecial method of range class failed
the ActiveSheet.Paste returns a "Run-time error '1004':
Paste method of Worksheet class failed
Although this code is not the cleanest, it all functions with the exception of the "pasting" onto 'sheetA' in Column Z. I also need the data pasted into AA if that can be included in a fix.
Thanks !
Here's (I hope) the same macro, but without .Select/.Activate, and a little tweaking. For instance, you don't need more than one "lastRow" variable. Since you really just reset it, you can use one.
Sub tester()
' First create, then SET, worksheet variables to hold the sheets. We use these when
' referring to ranges, cells, etc.
Dim aWS As Worksheet, bWS As Worksheet
Set aWS = Worksheets("SheetA")
Set bWS = Worksheets("SheetB")
Dim lastRow As Long 'AFAICT, you only need this one Last Row variable. Just update it each time.
Dim copyRng As Range
With wsB ' working with SheetA
lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
.Range("DL2:DL" & lrOne).AutoFilter Field:=116, Criteria1:="<>Apples"
lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
.Range("DG2:DG" & lastRow).AutoFilter Field:=111, Criteria1:=Target
lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
' We now SET the range we want to copy. We can avoid copy/paste by setting two ranges equal
' to eachother. For now, let's store the COPY RANGE in a Range variable
Set copyRng = .Range("DX2:DX" & lastRow).SpecialCells(xlCellTypeVisible)
End With 'bWS
Dim pasteRng As Range
With aWS
lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
.Range("A2:A" & lastRow).AutoFilter Field:=1, Criteria1:=Target
lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
Set pasteRng = .Range("Z2:Z" & lastRow).SpecialCells(xlCellTypeVisible)
End With 'aWS
pasteRng.Value = copyRng.Value
End Sub
The only hesitation I have is the pasting to SpecialCells. AFAIK, if the paste range is different than the copy range, you might get some errors. In any case, try the above and let me know what happens.
An important thing to pay attention to, especially when using multiple worksheets, is that you should be explicit with which sheet you want to get a Range(),Cells(),Rows(),Columns(),etc. Otherwise, it's going to get that info. from the ActiveSheet, whatever that may be.

Copying Data to another workbook

I use two workbooks (obviously based on the question:)), from the first one (as you will see in the code below) gets sorted by the data in column "B". The data in this column is just a number based on the month (11=November, December=12, etc.). For this question (and it will provide the answer for my other monthly workbooks), need to copy all the rows of data (columns A:AE) in column B to another workbook (which is already open), and paste the data into the empty row at the bottom. I have the sort part working fine. I am trying to add in the copy & paste function into the code, but can't get it to work. HELP!
Here is the code I have tried (but can't figure out how to get focus to the target workbook):
Sub Extract_Sort_1512_December()
' This line renames the worksheet to "Extract"
Application.ScreenUpdating = False
ActiveSheet.Name = "Extract"
' This line autofits the columns C, D, O, and P
Range("C:C,D:D,O:O,P:P").Columns.AutoFit
' This unhides any hidden rows
Cells.EntireRow.Hidden = False
Dim LR As Long
With ActiveWorkbook.Worksheets("Extract").Sort
With .SortFields
.Clear
.Add Key:=Range("B2:B2000"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
End With
.SetRange Range("A2:Z2000")
.Apply
End With
For LR = Range("B" & Rows.Count).End(xlUp).Row To 2 Step -1
If Range("B" & LR).Value <> "12" Then
Rows(LR).EntireRow.Hidden = True
End If
Next LR
Cells.WrapText = False
Sheets("Extract").Range("A2").Select
Dim LastRow As Integer, i As Integer, erow As Integer
LastRow = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Cells(i, 2) = “12” Then
Range(Cells(i, 1), Cells(i, 31)).Select
Selection.Copy
ActiveWorkbook(“Master File - Swivel - December 2015.xlsm”).Select
Worksheets(“Master”).Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
End If
Next i
Application.ScreenUpdating = True
End Sub
I have found this code below, but do not know how to insert it properly into my code above. The thing that makes me weary is that the workbooks are already open. The target workbook is located on our SharePoint site and I do not know how (or if) you can use VBA code to open it to your desktop.
Here is the other code:
Sub Demo()
Dim wbSource As Workbook
Dim wbTarget As Workbook
' First open both workbooks :
Set wbSource = Workbooks.Open(" ") ' <<< path to source workbook
Set wbTarget = ActiveWorkbook ' Workbooks.Open(" ") ' <<< path to destination workbook
'Now, transfer values from wbSource to wbTarget:
wbTarget.Sheets("Sheet1").Range("B2").Value = wbSource.Sheets("Sheet3").Range("H4")
wbTarget.Sheets("Sheet1").Range("B3").Value = wbSource.Sheets("Sheet3").Range("J10")
'Close source:
wbSource.Close
End Sub
I have modified your code slightly, but kept most of it as is.
I think the problem was related to the way in which you were trying to activate the workbook where the data was to be pasted. Normally the Activate command is used with workbooks, as opposed to Select. However, I bypassed the whole activation of the new workbook, because it would require you to then "re-activate" the original workbook before copying the next line. Otherwise you would be copying from the active workbook, which would now be the one to be pasted into. Please see the code - it should be fairly straightforward.
Sub Extract_Sort_1512_December()
Application.ScreenUpdating = False
' This line renames the worksheet to "Extract"
ActiveSheet.Name = "Extract"
' This line autofits the columns C, D, O, and P
Range("C:C,D:D,O:O,P:P").Columns.AutoFit
' This unhides any hidden rows
Cells.EntireRow.Hidden = False
Dim LR As Long
With ActiveWorkbook.Worksheets("Extract").Sort
With .SortFields
.Clear
.Add Key:=Range("B2:B2000"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
End With
.SetRange Range("A2:Z2000")
.Apply
End With
For LR = Range("B" & Rows.Count).End(xlUp).Row To 2 Step -1
If Not Range("B" & LR).Value = "12" Then
Rows(LR).EntireRow.Hidden = True
End If
Next LR
Cells.WrapText = False
Sheets("Extract").Range("A2").Select
Dim LastRow As Integer, i As Integer, erow As Integer
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Cells(i, 2) = "12" Then
' As opposed to selecting the cells, I just copy them directly
Range(Cells(i, 1), Cells(i, 31)).Copy
' As opposed to "Activating" the workbook, and selecting the sheet, I just paste the cells directly
With Workbooks("Master File - Swivel - December 2015.xlsm").Sheets("Master")
erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
.Cells(erow, 1).PasteSpecial xlPasteAll
End With
Application.CutCopyMode = False
End If
Next i
Application.ScreenUpdating = True
End Sub

Macro in Excel 2010

Sheet 1
E-Code E-Name
11621 Hari
12205 Dass
11709 Boss
11913 Pass
11755 Test
Sheet 2
E-Code
11621
11709
11913
11755
12205
I want to run a macro which automatically do the vlookup function in sheet 2 against the E-Code which are unique fields.
The macro which i have created is as below. However when i change the data it is not working.
Sub Macro()
Sheets("Sheet2").Select
Range("B2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],Sheet1!C[-1]:C,2,0)"
Range("B2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],Sheet1!C1:C2,2,0)"
Range("B2").Select
Selection.Copy
Range("B3:B6").Select
ActiveSheet.Paste
Range("A1").Select
End Sub
I have checked your code. It is working fine. However, if you increase the no of rows it will not take into account. Please find the below code which will find the no of rows in Sheet1 and Sheet2.
Sub Macro1()
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Set sht1 = ThisWorkbook.Sheets("Sheet1")
Set sht2 = ThisWorkbook.Sheets("sheet2")
Sh1Rows = sht1.Range("A" & Rows.Count).End(xlUp).Row
sh2rows = sht2.Range("A" & Rows.Count).End(xlUp).Row
sht2.Range("B2") = "=Vlookup(A2," & sht1.Name & "!" & sht1.Range("A2:B" & sh2rows).Address & ",2,false)"
sht2.Range("B2").Copy sht2.Range("B2:B" & sh2rows)
End Sub

Resources