Copy row based on cell value - excel

I am trying to search within a specific column for a "yes" value and copy the entire row of data if present into a new sheet.
So far I copy and paste a row which doesn't include a "yes". This results in four rows of the same data pasted instead of the four I need.
Dim rng As Range, cell As Range
Dim sht As Worksheet
Set sht = Worksheets("Output")
With sht
lastRow = .Range("R" & .Rows.Count).End(xlUp).Row
End With
If lastRow < 2 Then lastRow = 2
Set rng = sht.Range("R2:R" & lastRow)
For Each cell In rng
If cell.Value = "Yes" Then
ActiveCell.EntireRow.Copy
Worksheets("Callouts").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.PasteSpecial Paste:=xlPasteValues
End If
Next
End Sub

First you want iterate through each row, then each cell in the row to find the "Yes". Then you want to copy the row to the new sheet. Consider:
Dim rng As Range, cell As Range
Dim targetLastRow as Range
Dim sht As Worksheet
Set sht = Worksheets("Output")
'capture last row in source
sourceLastRow = sht.Range("R" & Rows.Count).End(xlUp).Row
If sourceLastRow < 2 Then sourceLastRow = 2
'set source rng
Set rng = sht.Range("R2:R" & lastRow)
'Capture last row in target sheet
targetLastRow = Sheets("Callouts").Range("A" & Rows.Count).End(xlUp).Row
'iterate through each row in source range
For each row in rng.rows
'iterate through each cell in row
For Each cell In row
If cell.Value = "Yes" Then
cell.EntireRow.Copy
Sheets("Callouts").Cells(targetLastRow, 1).PasteSpecial Paste:=xlPasteValues
'increment target to next row
targetLastRow = targetLastRow + 1
End If
Next
Next

Related

Looking for a way to Autofill Using a Variable Range

I'm looking for a way to autofill my formula down to the last row in the dataset (which is variable) using a range which is also variable. I have highlighted my issue below at the bottom.
Here is the code that I have now:
Sub MissingData()
Dim LastRow As Long
Dim LastCol As Long
Set ws = Worksheets("Insert Data")
With ws
Last Row = .Cells(.Rows.Count, 1).End(xlUp).Row
Last Col = .Cells(1, .Columns.Count).End(xlToLeft).Column
'Inserting Column Header next to the last column in the data set in row 1"
.Cells(1, LastCol + 1).Value = "Header"
'Inserting Formula next ot the last column in the data set in row 2"
.Cells(2, LastCol + 1).Formula = "=iferror(AJ2,""YES"")"
End With
Dim FoundCell As Range
'Looking for the Last Row in the Dataset"
'Column A:A will always be populated with data and will be the driver
'for how many rows are in the data set"
LR = Worksheets("Insert Data").Range("A:A").End(xlDown).Row
With ws
'I set this and then called it using select because my range above
'and the location of this cell could be variable"
Set FoundCell = .Cells(2, LastCol + 1)
FoundCell.Select
'Here lies my issue. Using this syntax the formula is filled all the way
'to the last row available in Excel which is like 1 million something.
'I just need it filled to the last now that i set above"
Selection.AutoFill Destination:=Range(ActiveCell, ActiveCell.End(xlDown))
End With
End Sub
A better alternative to AutoFill is to enter the formula in the entire range in one go. Is this what you are trying?
Option Explicit
Sub MissingData()
Dim LastRow As Long
Dim LastCol As Long
Dim ws As Worksheet
Dim LastColName As String
Set ws = Worksheets("Insert Data")
With ws
'~~> Find last row
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
'~~> Find last column and add 1 to it
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1
'~~> Get Column name from column number
' https://stackoverflow.com/questions/10106465/excel-column-number-from-column-name
LastColName = Split(.Cells(, LastCol).Address, "$")(1)
'~~> Add header
.Range(LastColName & 1).Value = "Header"
'~~> Add the formula in the entire range in ONE GO
' Example: Range("D2:D" & LastRow).Formula = "=IFERROR(AJ2,""YES"")"
.Range(LastColName & 2 & ":" & LastColName & LastRow).Formula = "=IFERROR(AJ2,""YES"")"
End With
End Sub

Excel VBA: Copy data from cell above in blank cells, but only in columns A-B

I have 5 columns of data. The data is grouped by employee name and number (cols A-B) and their respective pay types (col C). I need to
Copy employee name to blank cell below in col A
Copy employee number to blank cell below in col B
Add the word "Advance" in the blank cell in col C
Current code selects all blank cells in cols A-E and fills with the values from above:
Sub FillBlanksValueAbove1()
Dim sName As String
sName = ActiveSheet.Name
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim rng As Range
'Set variable ws Active Sheet name
Set ws = Sheets(sName)
With ws
'Get the last row and last column
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'Set the range
Set rng = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
rng.Select
'Select Blanks
rng.SpecialCells(xlCellTypeBlanks).Select
'Fill Blanks with value above
Selection.FormulaR1C1 = "=R[-1]C"
'Paste Formulas as Values
rng.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
End With
End Sub
This is what the spreadsheet looks like now:
This is what I need it to look like:
This is the end result I currently get:
Thank you so so much!
Test the next code, please. No need of any selection, a little simplified:
Sub FillBlanksValueAbove1()
Dim rng As Range, rngVis As Range
Dim ws As Worksheet, lastRow As Long
'Set variable ws Active Sheet name
Set ws = ActiveSheet
With ws
'Get the last row
lastRow = .Range("A" & .Rows.count).End(xlUp).Row
'Set the range
Set rng = .Range(.cells(1, 1), .cells(lastRow, 2)) 'Col B:C
Set rngVis = rng.SpecialCells(xlCellTypeBlanks)
'Fill ADVANCE in column C:C
rngVis.Offset(, 1).Value = "ADVANCE"
'Fill Blanks with value above
rngVis.FormulaR1C1 = "=R[-1]C"
'Paste Formulas as Values
rngVis.Value = rngVis.Value
End With
End Sub

Copy the row value from A:F where it indicates "This is not a date format" and paste the values in a specific column

In my code, it identifies every value in the column A "This is a date format" and "This is not a date format". But i need it to copy the value from A:F in the row that it states "This is not a date format" and paste it in specific cell above it like. Offset(-1, 2). Also delete the row of the cell 'That is not a date format' after the value copied. Any ideas thanks. Below is my code:
Dim strDate As String
Dim rng As Range, cell As Range
Set rng = Range("A2:A18")
With ThisWorkbook.Worksheets("Feuil1")
For Each cell In rng
MsgBox (cell.Value)
strDate = cell.Value
If IsDate(strDate) Then
MsgBox "This is a date format"
Else
MsgBox "This is not a date format"
'copy cell from A:E
Range("A" & ActiveCell.Row & ":F" & ActiveCell.Row).Copy
'Paste selected and copied in specific cell in offset(Row, Column)
Range("K" & ActiveCell.Row).Offset(-1, 2).PasteSpecial
'copy cell from A:E
'Paste selected and copied in specific cell in offset(Row, Column)
End If
Next cell
End With
End Sub
Try the next code, please. It works for all the A:A range (with data). If you need only up to A18, change lastRow = 18:
Sub testCopyNotDate_DeleteRow()
Dim sh As Worksheet, strDate As String, rngDel As Range
Dim lastRow As Long, i As Long
Set sh = ThisWorkbook.Worksheets("Feuil1")
lastRow = sh.Range("A" & Rows.count).End(xlUp).Row
For i = 2 To lastRow
If Not IsDate(sh.Range("A" & i).Value) Then
sh.Range("A" & i & ":F" & i).Copy Destination:=sh.Range("A" & i).Offset(-1, 2)
If rngDel Is Nothing Then
Set rngDel = sh.Range("A" & i)
Else
Set rngDel = Union(rngDel, sh.Range("A" & i))
End If
End If
Next i
If Not rngDel Is Nothing Then rngDel.EntireRow.Delete xlUp
End Sub
It would be very fast (for big ranges) deleting the rows at once...
Try this basic code to loop from the last row to the first row, copy the row if the first cell is not a date, and paste the data to the row above the current row starting at column M; then delete the current row.
With ThisWorkbook.Sheets("Feuil1") 'Id your workbook and worksheet using a `With` statement
For x = 18 To 1 Step -1 'loop through your rows from the last to the first
'Check if the data in column A of the current row is not a date
If IsDate(Range("A" & x)) = False Then
'Copy the range from columns A:F on the current row and paste on the row above starting at column M
.Range("A" & x & ":F" & x).Copy .Range("M" & x - 1)
'Delete the current row
.Rows(x).Delete
End If
Next x 'Loop to the next row
End With
Copy And Delete
Option Explicit
Sub copyAndDelete()
Const wsName As String = "Feuil1"
Const FirstRow As Long = 2
Const LastRowCol As Variant = "A"
Const srcCol As Variant = "A"
Const tgtCol As Variant = "M"
Const NumOfCells As Long = 6
Const RowOff As Long = -1
Dim wb As Workbook: Set wb = ThisWorkbook
' Define worksheet.
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
' Calculate Last Row (or not).
Dim LastRow As Long
' Either calculate LastRow (usually),
LastRow = ws.Cells(ws.Rows.Count, LastRowCol).End(xlUp).Row
' Or just use 18:
'LastRow = 18
' Check if there is any data.
If LastRow < FirstRow Then Exit Sub
' Calculate Column Offset.
Dim ColOff As Long
ColOff = ws.Columns(tgtCol).Column - ws.Columns(srcCol).Column
' Define Criteria Range.
Dim rng As Range: Set rng = ws.Range(ws.Cells(FirstRow, srcCol), _
ws.Cells(LastRow, srcCol))
' Loop through cells in Criteria Column.
Dim URng As Range, cell As Range, varDate As Variant
For Each cell In rng
varDate = cell.Value
If Not IsDate(varDate) Then
GoSub copyCells
GoSub collectCells
End If
Next cell
' Test with hidden.
If Not URng Is Nothing Then URng.EntireRow.Hidden = True
' When tested, outcomment the previous and uncomment the following line.
'If Not URng Is Nothing Then URng.EntireRow.Delete
Exit Sub
copyCells:
' Either (for values only)(faster):
cell.Offset(RowOff, ColOff).Resize(, NumOfCells).Value _
= cell.Resize(, NumOfCells).Value
' Or (including formats, formulas ...)(slower):
'cell.Resize(, NumOfCells).Copy _
cell.Offset(RowOff, ColOff).Resize(, NumOfCells)
Return
collectCells:
If Not URng Is Nothing Then
Set URng = Union(URng, cell)
Else
Set URng = cell
End If
Return
End Sub

find text and copy adjacent cell to different sheet

I need help. I need to search my worksheet and find a specific word ("substances"), then copy the value in the cell 2 columns over into a different sheet.
For example, in Sheet1, if "substances" was found in A4, then copy value from C4 and paste into Sheet2 under last filled row. I need to continue doing this for the entire worksheet. "Substances" does not occur sequentially, but always in column A (i.e. the first occurrence may be A4, the ext one might be in A16).
Here's what I have so far:
Dim Cell, cRange As Range
Set cRange = Sheets("Sheet1").Range("A1:A75")
For Each Cell In cRange
FindCounter = 0
If Cell.Value = "Substances" Then
FindCounter = FindCounter + 1
Sheets("Sheet1").Cell.Value(0, 2).Copy
Sheets("Sheet2").Range("A" & Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1).PasteSpecial xlPasteValues
End If
Next
Application.ScreenUpdating = True
Try this. Find is more efficient than looping (for reasons I have never fully understood).
Sub x()
Dim rFind As Range, s As String
With Sheets("Sheet1").Range("A1:A75")
Set rFind = .Find(What:="Substances", Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
s = rFind.Address
Do
Sheets("Sheet2").Range("A" & Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1).Value = rFind.Offset(, 2).Value
Set rFind = .FindNext(rFind)
Loop While rFind.Address <> s
End If
End With
End Sub
Alternative using for loop:
Sub Copy()
Dim i As Long
Dim lRow1 As Long, lRow2 As Long
Dim ws1 As Worksheet, ws2 As Worksheet
'set worksheets
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
'set last row to search for substances
lRow1 = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row
'start for loop
For i = 1 To lRow1
If ws1.Range("A" & i).Value = "Substances" Then
'assuming you want to paste into column A on sheet 2
'adjust as you need to
lRow2 = ws2.Range("A" & ws2.Rows.Count).End(xlUp).Row + 1
ws2.Range("A" & lRow2).Value = ws1.Range("A" & i).Offset(0, 2).Value
End If
Next
'clear objects
Set ws1 = Nothing
Set ws2 = Nothing
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

Resources