How to find value of cell above each cell - vba

I want to screen all sheets for values that starts with "D"
In the sheets I formed blocks (1 column, 4 rows) with
- owner
- area
- parcel (that is allways starting with a "D")
- year of transaction (blocks of 1 column and 4 rows).
I want to make a summary in sheet "Test".
I'm able to find the parcel, but how can I get the info from the cell above?
Sub Zoek_kavels()
Dim ws As Worksheet
Dim rng As Range
Dim Area
Dim Kavel As String
rij = 1
For Each ws In ActiveWorkbook.Sheets
Set rng = ws.UsedRange
For Each cell In rng
If Left(cell.Value, 1) = "D" Then 'Starts with D
Sheets("Test").Cells(rij, 1) = cell.Value 'Kavel D..
Cells(cell.row - 1, cell.Column).Select
Area = ActiveCell.Value
Sheets("Test").Cells(rij, 2) = Area 'Oppervlakte
Sheets("Test").Cells(rij, 3) = ws.Name 'Werkblad naam
rij = rij + 1
End If
Next
Next
End Sub

A nice simple loop should do the trick, you may have had spaces in the worksheet, that would throw off the used range.
Here is a different approach.
Sub Get_CellAboveD()
Dim LstRw As Long, sh As Worksheet, rng As Range, c As Range, ws As Worksheet, r As Long
Set ws = Sheets("Test")
For Each sh In Sheets
If sh.Name <> ws.Name Then
With sh
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A1:A" & LstRw)
If LstRw > 1 Then
For Each c In rng.Cells
If Left(c, 1) = "D" Then
r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
ws.Range("A" & r).Value = c
ws.Range("B" & r).Value = c.Offset(-1).Value
ws.Range("C" & r).Value = sh.Name
End If
Next c
End If
End With
End If
Next sh
End Sub

There are two important points (and two not so important) to take care of your code:
start from row 2, because you are using .row - 1. Thus, if you start at row 1, row-1 would throw an error;
try to avoid Select, ActiveCell, etc.;(How to avoid using Select in Excel VBA);
write comments in English, not in Dutch (also good idea for variable names as well, rij or kavel do not help a lot);
declare the type of your variables, e.g. dim Area as String or as Long or anything else;
Option Explicit
Sub ZoekKavels()
Dim ws As Worksheet
Dim rng As Range
Dim Kavel As String
Dim rij As Long
Dim cell As Range
rij = 2 'start from the second row to avoid errors in .Row-1
For Each ws In ActiveWorkbook.Worksheets
Set rng = ws.UsedRange
For Each cell In rng
If Left(cell, 1) = "D" Then
With Worksheets("Test")
.Cells(rij, 1) = cell
.Cells(rij, 2) = ws.Cells(cell.Row - 1, cell.Column)
.Cells(rij, 3) = ws.Name
End With
rij = rij + 1
End If
Next
Next
End Sub
Or you can use .Cells(rij, 2) = cell.Offset(-1, 0) instead of Cells(cell.Row - 1, cell.Column), as proposed in the comments by #Shai Rado.

Related

How to refer dynamic range from another sheet to active sheet cell through VBA

I am not getting dynamic range work sheet name in formula. Can anyone assist on this? I get the active sheet range in the formula as =COUNTIF(I3:I31,A3)
Sub Test_DaySumm()
Dim Rg As Range
wksMain.Select
Dim ws1 As Worksheet
Set ws1 = wksMain
If ws1.FilterMode = True Then ws1.ShowAllData
LastRow = ws1.Cells(Rows.Count, "I").End(xlUp).Row
Set MyRange = ws1.Range(Cells(3, 9), Cells(LastRow, 9))
wksDaySummary.Select
xRow = 3
Do Until wksDaySummary.Cells(xRow, 1) = ""
Set Rg = wksDaySummary.Cells(xRow, 2)
Rg.Formula = "=COUNTIF( " & MyRange.Address(0, 0) & "," & Rg.Offset(0, -1).Address(0, 0) & ")"
Rg.Value = Rg.Value
xRow = xRow + 1
DoEvents
Loop
End Sub
Have a look at the Range.Address Property documentary
.Address(RowAbsolute, ColumnAbsolute, ReferenceStyle, External, RelativeTo)
and use the External:=True parameter get get the worksheet name in the address too:
MyRange.Address(RowAbsolute:=False, ColumnAbsolute:=False, External:=True)
So instead of eg I3:I31 the result would be like 'Main Sheet'!I3:I31

Can't delete rows containing certain keyword within text

I have written a macro to remove rows containing certain text in it. If either of the keyword contains any text, the macro will delete the row. However, the macro doesn't work at all. Perhaps, i did something wrong in it. Hope somebody will help me rectify this. Thanks in advance.
Here is what I'm trying with:
Sub customized_row_removal()
Dim i As Long
i = 2
Do Until Cells(i, 1).Value = ""
If Cells(i, 1).Value = "mth" Or "rtd" Or "npt" Then
Cells(i, 1).Select
Selection.EntireRow.Delete
End If
i = i + 1
Loop
End Sub
The keyword within the text I was searching in to delete:
AIRLINE DRIVE OWNER mth
A rtd REPAIRS INC
AANA MICHAEL B ET AL
ABASS OLADOKUN
ABBOTT npt P
AIRLINE AANA MTH
ABASS REPAIRS NPT
Try like this.
What about Using Lcase.
Sub customized_row_removal()
Dim rngDB As Range, rngU As Range, rng As Range
Dim Ws As Worksheet
Set Ws = Sheets(1)
With Ws
Set rngDB = .Range("a2", .Range("a" & Rows.Count))
End With
For Each rng In rngDB
If InStr(LCase(rng), "mth") Or InStr(LCase(rng), "rtd") Or InStr(LCase(rng), "npt") Then
If rngU Is Nothing Then
Set rngU = rng
Else
Set rngU = Union(rngU, rng)
End If
End If
Next rng
If rngU Is Nothing Then
Else
rngU.EntireRow.Delete
End If
End Sub
VBA syntax of your Or is wrong,
If Cells(i, 1).Value = "mth" Or "rtd" Or "npt" Then
Should be:
If Cells(i, 1).Value = "mth" Or Cells(i, 1).Value = "rtd" Or Cells(i, 1).Value = "npt" Then
However, you need to use a string function, like Instr or Like to see if a certain string is found within a longer string.
Code
Option Explicit
Sub customized_row_removal()
Dim WordsArr As Variant
Dim WordsEl As Variant
Dim i As Long, LastRow As Long
Dim Sht As Worksheet
WordsArr = Array("mth", "rtd", "npt")
Set Sht = Worksheets("Sheet1")
With Sht
' get last row in column "A"
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = LastRow To 2 Step -1
For Each WordsEl In WordsArr
If LCase(.Cells(i, 1).Value) Like "*" & WordsEl & "*" Then
.Rows(i).Delete
End If
Next WordsEl
Next i
End With
End Sub
I try to make my code sample as I can if you have any question please ask
Private Sub remove_word_raw()
'PURPOSE: Clear out all cells that contain a specific word/phrase
Dim Rng As Range
Dim cell As Range
Dim ContainWord As String
'What range do you want to search?
Set Rng = Range("A2:A25")
'sub for the word
shorttext1 = "mth"
shorttext2 = "rtd"
shorttext3 = "npt"
'What phrase do you want to test for?
ContainWord1 = shorttext1
ContainWord2 = shorttext2
ContainWord3 = shorttext3
'Loop through each cell in range and test cell contents
For Each cell In Rng.Cells
If cell.Value2 = ContainWord1 Then cell.EntireRow.Delete
Next
For Each cell In Rng.Cells
If cell.Value2 = ContainWord2 Then cell.EntireRow.Delete
Next
For Each cell In Rng.Cells
If cell.Value2 = ContainWord3 Then cell.EntireRow.Delete
Next cell
End Sub

Color a column by searching a particular text in A:A

Assist me with a VBA to color column from A:G, by searching a specific text, say 'UK'in Column A
Try this. Code1 works on every sheet in the workbook but if you like for this to work for the active sheet then try Code2. For Code2 remember to write the correct sheets name. Hope it helps.
Here you can choose an index color: https://stackoverflow.com/a/25000926/7238313
Code1:
Sub rowhighlight()
Dim sht As Worksheet
Dim nlast As Long
For Each sht In ActiveWorkbook.Worksheets
sht.Select
nlast = Cells(Rows.Count, "A").End(xlUp).Row
For n = nlast To 2 Step -1
If sht.Cells(n, "A").Value = "UK" Then
sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
'different color number place here----------------^
End If
Next n
Next sht
End Sub
Code2:
Sub rowhighlight()
Dim nlast As Long
Sheets("sheetname").Activate
Set sht = ActiveWorkbook.ActiveSheet
nlast = Cells(Rows.Count, "A").End(xlUp).Row
For n = nlast To 2 Step -1
If sht.Cells(n, "A").Value = "UK" Then
sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
'different color number place here----------------^
End If
Next n
End Sub
a very short and dirty and rude code is the following:
Sub ColorColumns()
On Error Resume Next
Range("A1", Cells(Rows.Count, 1).End(xlUp)).Find(what:=Application.InputBox("Text to search:", , , , , , , 2), LookIn:=xlValues, lookat:=xlWhole).Resize(, 7).Interior.ColorIndex = 6
End Sub
You can use the following code. Remember to keep the sheet containing the table active when running the code. Alternatively, you can specify the sheet explicitly when setting the ws variable.
Sub SelectivelyColorARowRed()
Dim ws As Worksheet
Set ws = ActiveSheet
lng_lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim k As Long
For k = 2 To lng_lastrow
If Trim(ws.Cells(k, 1).Value) = "UK" Then
'you can also apply UCase if you want the search to be case-insensitive
'like: If UCase(Trim(ws.Cells(k, 1).Value)) = UCase("Uk") Then
ws.Range(Cells(k, 1), Cells(k, 7)).Interior.ColorIndex = 22
End If
Next k
End Sub

How to optimize the vba code to search value from different sheet

I have written this below code to automate search function for a value T5536
which is in A1 cell of sheet1 and compare the A1 cell value with a column from sheet2 which has n number of values.
When the A1 value T5536 matches the value from Sheet2 A column then it should update the Sheet1 with Corresponding ES or IS values.
If the ES value in Sheet2 has Indirect word or string then it should update IS value in sheet1.
Please find the below code for the same :-
Sub test()
Dim lrow As Long
Dim i, j As Variant
Dim ms, ws As Worksheet
Dim num, esr, isr,x As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set ms = Worksheets("sheet1")
Worksheets("Sheet2").Activate
ms.Cells(2, 3) = ""
ms.Cells(2, 2) = ""
Set ws = Worksheets("Sheet2")
num = WorksheetFunction.Match("number", Range("1:1"), 0)
esr = WorksheetFunction.Match("ES", Range("1:1"), 0)
isr = WorksheetFunction.Match("IS", Range("1:1"), 0)
x = sheet2.cells(sheet2.rows.count,"A").end(xlup).row
FoundRange = ms.Range("A1")
For i = 2 To x
If ws.Cells(i, num) = FoundRange Then
Worksheets("sheet1").Activate
ms.Cells(2, 3) = ws.Cells(i, isr)
If ws.Cells(i, es) = "indirect" Then
ms.Cells(2, 2) = ws.Cells(i, is)
Else
ms.Cells(2, 2) = ws.Cells(i, es)
End If
End If
If ms.Cells(2, 2) <> "" Then
Exit For
End If
Next i
End Sub
The following code will work and takes less time when there are only few values to match in sheet2 A column, but if there are n number of values in sheet2 then it will be difficult to go through for loop and fulfil the task, kindly help me in tweaking this code to search the value very fast and update the corresponding values.
I have attached the images which might help to analyse the query.
Check it out. You can edit this code as you require.
Sub loopExample()
Dim sh As Worksheet, ws As Worksheet
Dim LstRw As Long, Frng As Range
Dim rng As Range, c As Range, x
Set sh = Sheets("Sheet1")
Set ws = Sheets("Sheet2")
Set Frng = sh.Range("A1")
With ws
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A2:A" & LstRw)
End With
For Each c In rng.Cells
If c = Frng Then
x = IIf(c.Offset(0, 1) = "indirect", 2, 1)
sh.Range("B2") = c.Offset(0, x)
End If
Next c
End Sub

Copy cell content and paste it to another sheet multiple times

I am trying to copy value from two specific cells to specific cells in another sheet.
Problem is that I have many cells in first sheet and some of them are empty. Also paste is always 99 times, just range changes. Is there a loop to make everything more easy?
Here is my attempt
Sub copytry()
Worksheets("sheetI").Range("I17:J17").Copy _
Destination:=Worksheets("sheetII").Range("F1352:F1451")
Worksheets("sheetI").Range("I18:J18").Copy _
Destination:=Worksheets("sheetII").Range("F1452:F151")
End Sub
Practice using this,
Sub copytry()
Dim ws As Worksheet
Dim sh As Worksheet, lstrw As Long
Dim Rws As Long, Rng As Range, c As Range
Set ws = Worksheets("sheetI")
Set sh = Worksheets("sheetII")
With ws
Rws = .Cells(Rows.Count, "I").End(xlUp).Row
Set Rng = .Range(.Cells(17, "I"), .Cells(Rws, "I"))
For Each c In Rng.Cells
If c = "" Then c = "." 'Added to Code
lstrw = sh.Cells(Rows.Count, "A").End(xlUp).Row + 1
c.Range("A1:B1").Copy Destination:=sh.Range(sh.Cells(lstrw, 1), sh.Cells(lstrw + 99, 1))
Next c
End With
End Sub