Excel VBA - Target.EntireRow excluding two columns - vba

I am working on a spreadsheet that utilizes columns A:AV. I have it set to automatically copy and paste the entire row when a cell in column D has the text "Closed". I couldn't cut the row due to formatting that the sheet has, so instead I'm using this to clear the row Target.EntireRow.Value = "". My question is, is it possible to set the values of the entire row to "" while skipping over columns W and X? I have formulas in those columns that I don't want to be erased. Thanks for the help.

To clear all cells in a row except for columns W and X:
With Target.Parent
Union(.Range(.Cells(Target.Row, "A"), .Cells(Target.Row, "V")), _
.Range(.Cells(Target.Row, "Y"), .Cells(Target.Row, .Columns.Count))).ClearContents
End With

Related

Selecting a cell and copiying the corresponding cells in the row in VBA

I am trying to build a macro and I want to copy a row after selecting a specific cell with the filter. So I filter a cell in column "A" and then I want to copy all the cells in that row. The problem is that the rownumber corresponding to the selected cell may change, due to different datasets.
Below is the code:
Selection.AutoFilter
ActiveSheet.Range("$A$1:$DO$46").AutoFilter Field:=2, Criteria1:= _
"NAME"
Range("A5:DO5").Select
Selection.Copy
The point is that in VBA the selection is set at "A5:DO5", because in this specific dataset "NAME" is on "A5".
But in a different dataset "NAME" might be on "A9", but in VBA the selection of the row is still on "A5:DO5".
How can I make the selection of "NAME" and the copy of all the cells in the row of "NAME" linked to eachother?
I think the question could be a bit clearer, but here goes.
As I understand it you want to copy a row, say 5th row down, after a filter has been applied to hide some rows in between (5th visible row).
Or, you want to find "NAME" and copy the corresponding row, irrespective of what's hidden and what isn't.
(If I haven't got the above right, please let me know and/or consider clarifying the question)
Try something like this;
Dim C as Cell
Dim RowNum as Integer 'If you're looking for the 5th visible cell.
For each C in Range("A:A").SpecialCells(xltypeVisible)
RowNum = RowNum+1 'Count how many visible cells you've looped
If C.Value = "NAME" Then
'Or for the 5th visible cell, use 'If RowNum = 5 Then'
C.EntireRow.Copy
Exit For
End If
Next
Thank you for your answer. Unlukily, the code is not working.
To clarify:
I want to find "NAME" in Column "B" and copy the corresponding row of "NAME", irrespective of what's hidden and what isn't.
Now I have this code:
Dim C As Range
For Each C In Range("B:B")
If C.Value = "NAME" Then
C.EntireRow.Copy
Exit For
End If
Next
The code does copy a row, but not the row that corresponds with "NAME". Instead, it copies the first row in the active sheet.

VBA Subroutine to fill formula down column

I have a current Sub that organizes data certain way for me and even enters a formula within the first row of the worksheet, but I am running into the issue of wanting it to be able to adjust how far down to fill the formula based on an adjacent column's empty/not empty status. For example, each time I run a report, I will get an unpredictable amount of returned records that will fill out rows in column A, however, since I want to extract strings from those returned records into different Columns, I have to enter formulas for each iteration within the next three columns (B, C, and D). Is there a way to insert a line that will evaluate the number of rows in Column A that are not blank, and then fill out the formulas in Columns B, C, and D to that final row? (I know that tables will do this automatically once information is entered in the first row, but for logistical reasons, I cannot use tables).
My current code that fills out the formula in Column B, Row 2 is:
Range("B2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
Thanks!
The formula that you actually need is
=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))
instead of
=MID(A2,FIND("By:",A2)+3,22) '"=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
This checks if there is anything in cell A and then act "accordingly"
Also Excel allows you to enter formula in a range in one go. So if you want the formula to go into cells say, A1:A10, then you can use this
Range("A1:A10").Formula = "=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))"
Now how do we determine that 10? i.e the Last row. Simple
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change the name of the sheet as applicable
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find Last Row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B2:B" & lRow).Formula = "=IF(A2="""","""",MID(A2,FIND(""By:"",A2)+3,22))"
End With
End Sub
More About How To Find Last Row
You can use this to populate columns B:D based on Column A
Range("B2:D" & Range("A" & Rows.Count).End(xlUp).Row).Formula = _
"=MID($A2,FIND(""By:"",$A2)+3,22)"

Compare worksheets and insert new rows

I currently have two sheets with six columns of data, both in the same format, except that Sheet 1 has historic data and sheet 2 has newer data with some additional rows. Both sheets are sorted in order of the contents in the 2nd column followed by the 4th column.
I want to prepare a macro that compares both sheets and looks down the 2nd and 4th columns to identify the new rows in Sheet 2 that are not in Sheet 1 and color highlight these rows in Sheet 2. In addition, I would like the new rows from sheet 2 to be inserted into Sheet 1 in the correct order.
For Example
The reason for doing all this as opposed to just copying the entire contents of Sheet 2 into Sheet 1 is because sheet 1 has a number of formulas beyond the 6 columns which reference certain blocks of cells and it is require that these references be preserved. I currently have to manually insert each new row and given the amount of data being processed, this takes quite some time. I have tried adapting other macros that I found across the internet to perform this task but they don’t quite work.
Step #1: identify rows that are in sheet2 and not in sheet1
Create a new column E in both sheets with this formula:
=B2&D2
(starting from row 2 and auto fill it to the entire column)
in sheet2 create column F with this formula
=ISERR(VLOOKUP(Sheet2!E2,Sheet1!E:E,1,FALSE))
Now column F would be TRUE only for rows that aren't in sheet1.
Next you'll need to add conditional formatting for F=TRUE
Step #2: Copy the missing data
Filter rows from sheet2 with F=TRUE
Copy them to the end of sheet1
Sort sheet1
If you copy the data (excluding the header) from Sheet2 underneath the data in Sheet1 and subsequently a) remove duplicates then b) sort on columns B and D, you should achieve the results you are looking for.
Sub collect_and_sort()
With Sheets("sheet1")
Sheets("sheet2").Cells(1, 1).CurrentRegion.Offset(1, 0).Copy _
Destination:=.Cells(Rows.Count, 2).End(xlUp).Offset(1, -1)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=Array(2, 4), Header:=xlYes
.Cells.Sort Key1:=.Columns(2), Order1:=xlAscending, _
Key2:=.Columns(4), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
End With
End With
End Sub
From the data on two sheets like this (shown on one sheet for space considerations),
    
You will have this after the macro has run.
    
I will admit I am unclear on whether the 3000/b in Sheet1!B11:D11 was a typo or an actual duplicate record. The macro does reproduce your desired results.

select row based on cell value

I am working on a macro to move data from one sheet to another based on matching cell values.
Let's say I have 2 sheets, Sheet1 & Sheet2, respectively.
Sheet1 contains data that I wanted to be copied into Sheet2.
Sheet2 contains a value in column "C", and this value with have multiple matches in column "C" of
Sheet1 (which are already sorted and same values are grouped together).
My overall goal is to copy cells from Sheet1 to Sheet2 based on matching values in column "C". I want to insert these values one row below the row with matching column "C" values.
The difficulty lies in the fact that the range of values copied from Sheet1 to Sheet2 will differ with each different value in Column "c" of Sheet2, because there will be a different number of rows with respect to a particular cell value.
(I would show a simple picture for this, but it won't allow me to post a picture due to low post count - I can email this if needed for clarification)
I am okay with basic macro stuff and rely on the Macro Record for some stuff as well. But with my current knowledge and lack of the macro recorder's ability to make a macro like this, I am just stumped!
My request:
Help with macro that selects a range of cells based on matching cell values to copy
Help with inserting the copied range starting 1 row below the cell value of interest (cell value is row 2, insert cells starting at row 3)
Have this repeated for each value listed in Sheet2
I think I can figure the basic coding with this. If I can just get help with the particular string that does what I am looking for would be great! I am not trying to just be handed the answer, but I have been working on this issue for 8+hrs and can't find anything online that is similar to this...
This code assumes that you have sorted the data as you have in the example:
Sub transfer()
'If everything is sorted, you can do it like this:
Dim x, y 'x is the sheet1 row, y is the sheet2 row
y = 2 'they start at the same place x = 2, y = 2
For x = 2 To Sheets(1).Cells(Sheets(1).Rows.Count, "A").End(xlUp).Row
If Sheets(1).Cells(x, 1) = Sheets(2).Cells(y, 1) Then 'If the cell value matches
Sheets(1).Range("A" & x).Copy 'Copy the cell value from Sheet1
Sheets(2).Cells(y + 1, 1).Insert Shift:=xlDown 'And insert it below the Sheet2 Cell
'Then copy the rest of the data (columns C and D)
Sheets(1).Range("C" & x & ":D" & x).Copy Destination:=Sheets(2).Cells(y + 1, 2)
Else
x = x - 1 'We haven't found a match for this cell yet so check it again
End If
y = y + 1 'After incrementing y
Next x
End Sub
Sorry for slow reply - I can explain the code to you soon if need be!
Hope this helps! :)
I wrote this specifically for the example you gave me, so hopefully you are able to build upon this concept if your needs change.

Clear all cells in column who = ""?

So, I have a script that is plotting data points for me, and I'm running into an issue where there are several blank spots in the data. Of of my columns is calculated, and I have a formula that sets it equal to "" if more than 0 cells that are used in the calculation are blank. The plots that use the blank cells work fine to show gaps in the data, but Excel doesn't evaluate a cell that has a formula that results in "" as blank.
Therefore, I need to set up some code that can search the entire column of data and clear the formula out of the cells whose value equal "", thereby making them blank and displaying as gaps in the plot.
I know I can use the Find and What commands to find the first cell that is evaluated as "", but how can I use it to find all the cells in the column?
The row range for the data is always constant, between 4 and 243, and the column number I am searching (within a loop) evaluates as 3*(iCounter - 1) + 2, if that helps anyone.
(The range I am searching is equal to Range(Cells(4, 3*(iCounter - 1) + 2), Cells(243, 3*(iCounter - 1) + 2))
Click on any cell in the column you wish to cleanup and run this:
Sub ClearThem()
Dim BigR As Range, r As Range
Set BigR = Intersect(ActiveCell.EntireColumn, ActiveSheet.UsedRange)
For Each r In BigR
If r.Value = "" Then r.Clear
Next r
End Sub