Excel VBA button. Copy rows from Sheet1 to Sheet2 / Condition: column value - excel

I'm using code below to copy rows from Sheet1 to Sheet2.
I have 3 questions about.
Why this function always copy row A2? Even if value is "0".
How to copy just value, no formatting?
Is it possible to skip column B when copy? "C" from Sheet1 will be "B" in Sheet2, etc.
Sub COPY_SA()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, rngToCopy As Range
Dim lastrow As Long
'change Sheets to suit
Set ws1 = ThisWorkbook.Worksheets("SA")
Set ws2 = ThisWorkbook.Worksheets("JC_input")
With ws1
'assumung that your data stored in column A:D, Sheet1
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A2:D" & lastrow)
'clear all filters
.AutoFilterMode = False
With rng
'apply filter
.AutoFilter Field:=4, Criteria1:=">0"
On Error Resume Next
'get only visible rows
Set rngToCopy = .SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
'copy range
If Not rngToCopy Is Nothing Then rngToCopy.CopyDestination:=ws2.Range("A2")
'clear all filters
.AutoFilterMode = False
End With
Application.CutCopyMode = False End Sub
I manage to modify like below. Still have issue with range in Worksheet "ws1". Cannot set filter in second row and copy range from row 3. That is why added: "ws2.Rows(3).Delete". Code always copy row 1.
Row 1 got some comments.
Row 2 got column names.
Sub COPY_SA()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, rngToCopy As Range
Dim lastrow As Long
'change Sheets to suit
Set ws1 = ThisWorkbook.Worksheets("SA")
Set ws2 = ThisWorkbook.Worksheets("JC_input")
With ws1
'assumung that data stored in column C:E, Sheet1
lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
'can not make range from row 3 ???
Set rng = .Range("C1:E" & lastrow)
'clear all filters
.AutoFilterMode = False
With rng
'apply filter with criteria in column 3 of range C:E
'can not make filter in row 2 ???
.AutoFilter Field:=3, Criteria1:=">0"
On Error Resume Next
'get only visible rows
Set rngToCopy = .SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
'copy range
If Not rngToCopy Is Nothing Then rngToCopy.Range("A:C").Copy
'paste from row 3
ws2.Range("A3").PasteSpecial Paste:=xlValues
'delete no needed row
ws2.Rows(3).Delete
'clear all filters
.AutoFilterMode = False
End With
Application.CutCopyMode = False
If Not ActiveSheet.AutoFilterMode Then
ws1.Range("2:2").AutoFilter
End If
End Sub

Try this quick fix, assuming your headers on both sheets are in the first row:
Sub COPY_SA()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, rngToCopy As Range
Dim lastrow As Long
'change Sheets to suit
Set ws1 = ThisWorkbook.Worksheets("SA")
Set ws2 = ThisWorkbook.Worksheets("JC_input")
With ws1
'assumung that your data stored in column A:D, Sheet1
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A1:D" & lastrow)
'clear all filters
.AutoFilterMode = False
With rng
'apply filter
.AutoFilter Field:=4, Criteria1:=">0"
On Error Resume Next
'get only visible rows
Set rngToCopy = .SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
'copy range
If Not rngToCopy Is Nothing Then rngToCopy.Range("A:A,C:D").Copy
ws2.Range("A1").PasteSpecial Paste:=xlValues
'clear all filters
.AutoFilterMode = False
End With
Application.CutCopyMode = False
End Sub
To answer your questions:
Why this function always copy row A2? Even if value is "0".
That's because you have set a range starting from the second row and applied a filter to it.
We can change that in the code through setting the range from A1:D & Lastrow and also paste it to ws2.Range("A1").
How to copy just value, no formatting?
Yes it's possible, but you'll need to copy and paste as xlValues as explained by #Peh here
The change in code therefore is to .Copy a range and in the next line .PasteSpecial the xlValues.
Is it possible to skip column B when copy? "C" from Sheet1 will be "B" in Sheet2, etc.
Yes instead of copying the whole range, we can specify which columns you would want to copy, this can be a non-contiguous range of columns.
We can change the .Copy part to include only these specific columns we need.
I'm sure the whole thing can be written neater but this should at least do what you are after.

Related

How to implement cell select in VBA excel macro

I have a macro to copy data from ws1 (worksheet1) to ws2 (worksheet2).
I want to select cell G2 in ws2.
If I use .Range("G2").Select do not work.
If I use ws2.Range("G2").Select result is debug error (Run-time error '1004': Select method of Range class failed). I was trying few places and combinations. No idea how to select G2 and come back ws1 at the end of macro...
Macro:
Sub COPY_SA()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, rngToCopy As Range
Dim lastrow As Long
'change Sheets to suit
Set ws1 = ThisWorkbook.Worksheets("SA")
Set ws2 = ThisWorkbook.Worksheets("JC_input")
With ws1
'assumung that data stored in column C:E, Sheet1
lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
'can not make range from row 3 ???
Set rng = .Range("C1:F" & lastrow)
'clear all filters
.AutoFilterMode = False
With rng
'apply filter with criteria in column 3 of range C:E
'can not make filter in row 2 ???
.AutoFilter Field:=3, Criteria1:=">0"
On Error Resume Next
'get only visible rows
Set rngToCopy = .SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
'copy range
If Not rngToCopy Is Nothing Then rngToCopy.Range("A:D").Copy
'paste from row 3
ws2.Range("A3").PasteSpecial Paste:=xlValues
'delete no needed row
ws2.Rows(3).Delete
ws2.UsedRange.Columns("C:E").Calculate
'clear all filters
.AutoFilterMode = False
End With
Application.CutCopyMode = False
If Not ActiveSheet.AutoFilterMode Then
ws1.Range("2:2").AutoFilter
End If
End Sub

How to copy the full row from one sheet to another if the column C is marked as Y

I have three sheets in a workbook and I want to copy all the rows from all the first three sheets into sheet 4 which has the column 'C' marked as Y.
I'm answering this question, because I'm bored.
The code below assigns the worksheets to filter to an array, loops thru the array, filters the range, then copies the visible cells in the filter data. If "A1" is empty; it will paste the copied data from each worksheet to Range("A1"), else it will paste the data to the first empty cell in "column A". Change the worksheet names as required.
Sub FltrPste()
Dim wb As Workbook, shtArr As Variant, wsDest As Worksheet, i As Long, lRow4 As Long
Set wb = ThisWorkbook
shtArr = Array("Sheet1", "Sheet2", "Sheet3")
Set wsDest = wb.Sheets("Sheet4")
lRow = wsDest.Range("A" & Rows.Count).End(xlUp).Row
For i = LBound(shtArr) To UBound(shtArr)
With wb.Sheets(shtArr(i)).Range("A1").CurrentRegion
.AutoFilter
.AutoFilter Field:=3, Criteria1:="y"
.Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Copy
If Range("A1") = "" Then
wsDest.Cells(1, 1).PasteSpecial xlPasteValues
Else
wsDest.Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial xlPasteValues
End If
.AutoFilter
End With
Next i
End Sub

Choosing Specific Cells in VBA?

I've tried multiple codes without luck. I have an excel sheet with 1800 rows and the following columns: ProgramCode, StudyBoard, FacultyID and ProgramType.
In the StudyBoard column there are some cells that are empty. I will then find all the empty cells in StudyBoard and their corresponding information from the other columns. Once I've found the desired cells, they must be overwritten in a new sheet.
I have the following codes, and couldn't continue, because even what I try isn't working.
Dim ws As Worksheet
Dim StudyBoardCol As Range
Dim PromgramCodeCol As Range
Dim rndCell As Range
Dim foundId As Variant
Dim msg As String
Dim FacultyIdCol As Range
Dim ProgramTypeLetter As Range
Set ws = ThisWorkbook.Worksheets("SSBB")
Set StudyBoardCol = ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
Set ProgramCodeCol = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row)
Set FacultyIdCol = ws.Range("C2:C" & ws.Cells(ws.Rows.Count, "C").End(xlUp).Row)
Set ProgramTypeLetter = ws.Range("D2:D" & ws.Cells(ws.Rows.Count, "D").End(xlUp).Row)
For i = 2 To 1800
Set rndCell = StudyBoardCol.Cells(Int(Rnd * StudyBoardCol.Cells.Count) + 1)
FacultyIdCol = Application.Match(rndCell.Value, ProgramCodeCol, 0)
ProgramTypeLetter = Application.Match(rndCell.Value, ProgramCodeCol, 0)
You could use SpecialCells to “isolate” blank ones
Dim cell As Range
Dim newSheet As Worksheet
Set newSheet = Sheets.Add
With ThisWorkbook.WorkSheets("SSBB") ‘reference “SSBB” sheet
For Each cell in .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeBlanks) ‘ loop through referenced sheet column A blank cells from row 2 down to last not empty one
cell.Resize(,3).Copy destination:=newSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1) ‘ copy range next to current cell and paste to newSheet column A first empty cell
Next
End With
Or use Autofilter (you probably want to add a test that cells are present to be copied before attempting to set rng
Option Explicit
Public Sub TransferBlankStudyBoard()
Dim rng As Range
With ThisWorkbook.Worksheets("SSBB").UsedRange 'Or limit to columns A:D
.AutoFilter
.AutoFilter Field:=1, Criteria1:="="
Set rng = ActiveSheet.AutoFilter.Range
rng.Offset(1, 0).Resize(rng.Rows.Count - 1).Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
rng.Offset(1, 0).Resize(rng.Rows.Count - 1).EntireRow.Delete
.AutoFilter
End With
End Sub

How to write a macro to filter a column and take out the required value?

I need a macro that need to filter a column and to take out the required date value along with the cell position (i.e say "4/22/2018" cell position "A9 or just 9"). Kindly help me out to fix this issue
See the code that I wrote below
Dim Date As String
Date = Sheets("alldata")
Rows("3:3").Select.AutoFilter.Range("$A$3:$AA$606").AutoFilter , Field:=1, Criterial:="#VALUE!"
Range("A3").Select.xlFilterValues.offset(1, 0).Copy.value
Sheets("Log").Cells(2, "AF").value = Date
Is this what you are trying?
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Set ws = Sheets("alldata")
With ws
Set rng = .Range("$A$3:$A$606")
'~~> Remove any filters
.AutoFilterMode = False
With rng
.AutoFilter Field:=1, Criteria1:="<>#VALUE!"
'~~> Get the Row Number
MsgBox .Offset(1, 0).SpecialCells(xlCellTypeVisible).Row
'~~> Get The cell Address
MsgBox .Offset(1, 0).SpecialCells(xlCellTypeVisible).Cells(1, 1).Address
'~~> Get the Date
Sheets("Log").Cells(2, "AF").Value = _
.Offset(1, 0).SpecialCells(xlCellTypeVisible).Cells(1, 1).Value
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
End Sub
The following will filter the dates and for each date it will copy the value into Sheet Log in Column AF:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("alldata")
Dim wsLog As Worksheet: Set wsLog = Sheets("Log")
'declare and set your worksheet, amend as required
Dim LastRow As Long, LogLastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
Dim c As Range, rng As Range
ws.Rows("3:3").AutoFilter
ws.Range("$A$3:$AA$" & LastRow).AutoFilter Field:=1, Operator:=xlFilterValues, Criteria2:=Array(0, "01/01/2018")
Set rng = ws.Range("$A$4:$A$" & LastRow).SpecialCells(xlCellTypeVisible)
For Each c In rng
LogLastRow = wsLog.Cells(wsLog.Rows.Count, "AF").End(xlUp).Row
c.Copy Destination:=wsLog.Cells(LogLastRow, "AF")
'if instead of copying the value, you want to return its address,
'you can get the address by using "c.Address" for each value in the range
Next c
End Sub

Copying only visible from one sheet to another (with blanks in between)

Apologies editing .I have this below code which copies data of one row from 1 sheet to another (there are blanks in between). The code works fine, however I would like it copy only visible fields from sheet 1 (filters already applied).
This is copying the entire column U irrespective of the filters applied (filters are applied I column 10 and 38)
With Worksheets("Sheet1")
Set SrcRng = .Range(.Cells(1, "U"), .Cells(.Rows.Count, "U").End(xlUp))
End With
Worksheets("Sheet2").range("I1").Resize(SrcRng.Rows.Count, 1).Value = SrcRng.Value'
Please help
Try:
Sub CopyVisible()
Dim ws As Worksheet, ws2 As Worksheet
Dim SrcRange As Range, CpyRng As Range
Dim LRow As Long
Set ws = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
If ws.AutoFilterMode Then ws.AutoFilter.ShowAllData 'Removes Previous Filters
With ws
LRow = .Cells(.Rows.Count, 8).End(xlUp).Row 'Check Col "H" for last data
Set SrcRng = .Range(.Cells(1, 1), .Cells(LRow, 39)) 'Range with Data
With SrcRng
.AutoFilter Field:=39, Criteria1:="Blue"
.AutoFilter Field:=8, Criteria1:="Pass"
.AutoFilter Field:=10, Criteria1:="<>"
End With
For i = 1 To LRow 'Loop through all Rows
If Not .Cells(i, 1).EntireRow.Hidden Then 'Checks if Row is Hidden
If CpyRng Is Nothing Then
Set CpyRng = .Range("U" & i)
Else
Set CpyRng = Union(CpyRng, .Range("U" & i))
End If
End If
Next i
End With
ws.AutoFilter.ShowAllData 'Remove Filters
CpyRng.Copy ws2.Range("I1") 'Copy and Paste
End Sub
Will apply filters to all Columns from 1 to 39 and filter with the wanted criteria. Creates range with all visible rows in Col U and paste them into Sheet2 into Col I.

Resources