select adjacent cell in entire column VBA - vba

Code :
Option Explicit
Sub selectAdjacentBelowCells()
Dim r, c As Integer
Dim r1, r2, c1, c2 As Integer
Dim i As Integer
Dim j As Integer
Dim st As String
Dim lastRow As Integer
With ActiveCell
r = .Row
c = .Column
End With
r1 = r
r2 = r
lastRow = ActiveSheet.Cells(Rows.Count, c).End(xlUp).Row
Dim value As Integer
value = Cells(r, c).value
Dim value1 As Integer
Dim value2 As Integer
Dim myUnion As Range
Dim myCell As Range
For i = r1 To lastRow - 1
'selects adjacent cells below
value1 = Cells(i + 1, c).value
If (value1 = value) Then
Range(Cells(i, c), Cells(i + 1, c)).Select
Else
Exit For
End If
Next
Dim x As Integer
x = Cells(r2 - 1, c).value
For x = r2 To (r2 + 1) - r2 Step -1
'selects adjacent cells above
value2 = Cells(x - 1, c).value
If (value2 = value) Then
Range(Cells(r, c), Cells(x - 1, c)).Select
Else
Exit For
End If
Next
End Sub
Column in excel :
10
20
30
40
50
60
60(this cell is selected and then vba code is executed)
60
70
80
90
I need to select adjacent cells in entire column. It selects adjacent cells, but first it selects adjacent cells below and then above. But the selection changes to above cells and below cells are deselected after the first piece of code runs.
I know it can be done through Union, I tried using it but I got errors everytime. Got argument is not optional error and then I had to remove the Union code and the above code is what I now have.

Please give this a try to see if that works for you.
Sub selectAdjacentBelowCells()
Dim targetCell As Range, Rng As Range, cell As Range, LastCell As Range, uRng As Range
Dim lr As Long
Dim firstAddress As String
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set targetCell = ActiveCell
Set LastCell = Range("A:A").SpecialCells(xlCellTypeLastCell)
With Range("A1:A" & lr)
Set cell = .Find(what:=targetCell.value, after:=LastCell, LookIn:=xlValues, lookat:=xlWhole)
If Not cell Is Nothing Then
firstAddress = cell.Address
Do
If uRng Is Nothing Then
Set uRng = cell
Else
Set uRng = Union(uRng, cell)
End If
Set cell = .FindNext(cell)
Loop While Not cell Is Nothing And cell.Address <> firstAddress
End If
End With
For Each Rng In uRng.Areas
If Not Intersect(Rng, targetCell) Is Nothing Then
Rng.Select
Exit For
End If
Next Rng
End Sub

Related

Loop through range and if cell contains value copy to next empty cell in column

I am having real difficulty finding anything that has my query. I can find the different pieces of what I need but cannot put it together.
What I need to do is look through a set range and if value is between 0.001 and 0.26 then
copy cell and paste in next empty cell in column ("DA"), also copy cell from the same row that the value was found but copy from column ("C") and paste in next to column ("DB").
I know I have to loop through with an If statement, and will have to offset cell when it finds match to criteria. but I cannot put it together.
I have tried the following pieces of code.
Sub COPYcell()
Dim Last As Long
Dim i As Long, unionRng As Range
Last = 61
Dim lastrow As Long
lastrow = Sheets("Sheet1").Range("DA100").End(xlUp).Row
For i = 5 To Last
If (.Cells(i, "J").Value) >= 0.01 And (.Cells(i, "J").Value) <= 0.26 Then
'Cells(i, "DA").Value = Cells(i, "J").Value
Range(i, "J").Copy = Range("DA" & lastrow)
Cells(i, "J").Offset(, -8) = Range("DB" & lastrow)
Range("DC" & lastrow) = "July"
End If
Next i
End Sub
Try the following:
Option Explicit
Public Sub COPYcell()
Dim last As Long, sht1 As Worksheet
Dim i As Long, unionRng As Range, lastrow As Long, nextRow
Application.ScreenUpdating = False
Set sht1 = Worksheets("Sheet1")
last = 61
With sht1
lastrow = .Cells(.Rows.Count, "DA").End(xlUp).Row
nextRow = IIf(lastrow = 1, 1, lastrow + 1)
For i = 5 To last
If .Cells(i, "J").Value >= 0.01 And .Cells(i, "J").Value <= 0.26 Then '1%=26%
If Not unionRng Is Nothing Then
Set unionRng = Union(unionRng, .Cells(i, "J"))
Else
Set unionRng = .Cells(i, "J")
End If
End If
Next i
If Not unionRng Is Nothing Then
unionRng.Copy .Range("DA" & nextRow)
unionRng.Offset(0, -7).Copy .Range("DB" & nextRow)
End If
End With
Application.ScreenUpdating = False
End Sub
Your current code was giving me errors about range objects. I kept it simple and assigned cell values to cell values. Also, I am not sure if you meant .01 or .001. You may fiddle with that. The issue I saw was that as you find more matches, you want lastrow to go up so you are writing in what is now the last row, not what once was. You also had some unused variables pasted in, so I simplified. Here is the result.
Sub COPYCell()
Dim Last As Long
Dim i As Long
Last = 61
Dim lastrow As Long
lastrow = Sheets("Sheet1").Range("DA100").End(xlUp).Row + 1
For i = 5 To Last
If (Cells(i, "J").Value <= 0.26) And (Cells(i, "J").Value >= 0.001) Then
Cells(lastrow, "DA").Value = Cells(i, "J").Value
Cells(lastrow, "DB").Value = Cells(i, "C").Value
Cells(lastrow, "DC").Value = "July"
lastrow = lastrow + 1
End If
Next i
End Sub
EDIT Added +1 on lastRow per comment. I had tested where I had none yet.
You need to loop your range and inside loop check if you cell is not empty copy the cell value and in else paste in next empty cell.
Sample code:
Sub Func ()
Dim rng As Range, cell As Range
Set rng = Range("A1:A3")
For Each cell In rng
If (IsEmpty(cell.value))
Cell.paste()
Else
cell.copy()
End if
Next cell
End sub
The code is not tested because I typed it on a phone.

VBA Type Runtime 13 Error

I am wondering if someone can help me with this question. I have written a macro with the objective of deleting selected rows based upon whether or not all cells in a row contain the value "<0.01". The problem is when the program tries to process the if statement it errors out.
Any help would be appreciated.
Sub deleteRows()
Dim rng As Long
Dim FirstCol, LastCol As Long
Set UsedRng = ActiveSheet.UsedRange
FirstCol = UsedRng(1).Column
LastCol = UsedRng(UsedRng.Cells.Count).Column
rng = Application.Selection.Rows.Count
For i = rng To 1 Step -1
if Range(Cells(i, FirstCol), Cells(i, LastCol)) = "<0.01" Then
Rows(i).EntireRow.Delete
End If
Next i
End Sub
New code that i wrote
`Sub for3()
Dim ma, r, c As Range
Dim counter As Long
Dim deletenum As Long
Dim firstcol As Variant
Set ma = Application.Selection
Set r = ma.Rows
Set c = ma.Columns
counter = 0
deletenum = c.Count
firstcol = ma(1).Column
For Each r In ma
For Each c In r
If c.Column = firstcol Then
counter = 0
End If
If c.Text = "<0.01" Then
counter = counter + 1
End If
If counter = deletenum Then
r.EntireRow.Delete
ma.Offset(1, 0).Activate
End If
Next c
Next r
End Sub
`
You can use the Find function per row instead:
Dim FndRng As Range
For i = rng To 1 Step -1
Set FndRng = Range(Cells(i, FirstCol), Cells(i, LastCol)).Find(What:="<0.01", LookIn:=xlValues, LookAt:=xlWhole)
If Not FndRng Is Nothing Then ' find was successful
Rows(i).Delete
End If
Next
Edit 1: check that all cells in row equal to "<0.01".
For i = rng To 1 Step -1
If WorksheetFunction.CountIf(Range(Cells(i, FirstCol), Cells(i, LastCol)), "<0.01") = Range(Cells(i, FirstCol), Cells(i, LastCol)).Cells.Count Then
Rows(i).Delete
End If
Next I
Edit 2:
Option Explicit
Sub t()
Dim Rng As Range
Dim firstCol As Long, LastCol As Long
Dim firstRow As Long, LastRow As Long
Dim i As Long
Dim C As Range
Set Rng = Selection ' only if you realy need to
' calculate the first and last column of the Selection
firstCol = Rng(1).Column
LastCol = Rng.Columns.Count + firstCol - 1
' calculate the first and last Row of the Selection
firstRow = Rng(1).Row
LastRow = Rng.Rows.Count + firstRow - 1
' loop backwards, for the Selection last row, until the first row of the selection
For i = LastRow To firstRow Step -1
' loop through current's row cells
For Each C In Range(Cells(i, firstCol), Cells(i, LastCol))
If C.Value2 <> "<0.01" Then
GoTo ExitLoop
End If
Next C
Rows(i).Delete
ExitLoop:
Next i
End Sub
your test expression might look like:
Join(WorksheetFunction.Transpose(WorksheetFunction.Transpose(Range(Cells(i, FirstCol), Cells(i, LastCol)).Value)), " ") Like "*<0.01*"

VBA Excel match Copy Paste If Else

If Cell.value from Sheet2.Column"A" has no match in Sheet("Civil").Column"A" than copy that cell into Sheets("Sheet2).Column "D"
Correct Results
Correct result should look like on the attached picture but I have problem with
writing a correct code to fill Sheets("Sheet2).Column "D"
Sub NewSearch_A()
Dim cell As Range, rng As Range, rng2 As Range, rng3 As Range, cell1 As Range, n As Integer, m As Integer
Set rng = Sheets("Civil").Range("A2:A1000")
Set rng2 = Sheets("Sheet2").Range("A1:A100")
Set rng3 = Sheets("Sheet2").Range("C1:C100")
Set rng4 = Sheets("Sheet2").Range("D1:D100")
n = 1
m = 1
For Each cell In rng
n = n + 1
For Each cell1 In rng2
m = m + 1
If cell.Value = cell1.Value Then
Sheets("Sheet2").Range("C" & m & ":C" & m).Value = Sheets("Civil").Range("B" & n & ":B" & n).Value
Else
' ????????????????????????????????????????????????
End If
Next cell1
m = 1
Next cell
ActiveSheet.Columns("A:C").AutoFit
End Sub
Avoid the second loop with a WorksheetFunction MATCH function.
Sub NewSearch_A()
Dim rw As Long, mtch As Variant, wsc As Worksheet
Set wsc = Worksheets("Civil")
With Worksheets("Sheet2")
For rw = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
mtch = Application.Match(.Cells(rw, "A").Value2, wsc.Columns("A"), 0)
If IsError(mtch) Then
.Cells(rw, "D") = .Cells(rw, "A").Value2
Else
.Cells(rw, "C") = wsc.Cells(mtch, "B").Value2
End If
Next rw
End With
End Sub

Join cells based on value of a cell vba

I am trying to join cells in a row if a value exists in a cell in that row.
The data has been imported from a .txt file and various sub headers are split along 2, 3 or 4 columns.
The cells cant be merged as the data will only be kept from the first cell.
The only words which are always constant are "contain" and "for" in column B.
What I've tried resembles this:
If cell.Value like "contain", or "for" then join all cells from column "A" to column "H" into column "B", align them centrally and make them bold.
thanks, in advance, for any help.
Edit Here is the code:
Sub Joining()
Dim N As Long, i As Long, r1 As Range, r2 As Range
Dim z As Long
Dim arr() As Variant
z = 1
With Activesheet
N = .Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If .Cells(i, "B").Value Like "Summary*" Then
arr = .Range(.Cells(i, "A"), .Cells(i, "H")).Value
.Cells(z, "B").Value = Join(arr, " ")
z = z + 1
End If
Next i
End With
End Sub
Not sure if this is exactly what you want but it will get you close:
Sub summary()
Dim sh1 As Worksheet, sh2 As Worksheet
Dim N As Long, i As Long, r1 As Range, r2 As Range
Dim z As Long
Dim arr() As Variant
z = 1
Set sh1 = ActiveSheet
With ActiveWorkbook
Set sh2 = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With
With sh1
N = .Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If .Cells(i, "A").Value Like "Summary*" Then
arr = .Range(.Cells(i, "A"), .Cells(i, "H")).Value
sh2.Cells(z, "A").Value = Join(arr, " ")
z = z + 1
End If
Next i
End With
End Sub
Ok, so I've created an answer, but it ain't pretty (kinda like the whole project I've created).
It works although I'm sure there is a much simpler way of creating it.
Maybe someone can have a go at cleaning it up?
Sub SelRows()
Dim ocell As Range
Dim rng As Range
Dim r2 As Range
For Each ocell In Range("B1:B1000")
If ocell.Value Like "*contain*" Then
Set r2 = Intersect(ocell.EntireRow, Columns("A:G"))
If rng Is Nothing Then
Set rng = Intersect(ocell.EntireRow, Columns("A:G"))
Else
Set rng = Union(rng, r2)
End If
End If
Next
Call JoinAndMerge
If Not rng Is Nothing Then rng.Select
Set rng = Nothing
Set ocell = Nothing
End Sub
Private Sub JoinAndMerge()
Dim outputText As String, Rw As Range, cell As Range
delim = " "
Application.ScreenUpdating = False
For Each Rw In Selection.Rows
For Each cell In Rw.Cells
outputText = outputText & cell.Value & delim
Next cell
With Rw
.Clear
.Cells(1).Value = outputText
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
End With
outputText = ""
Next Rw
Application.ScreenUpdating = True
End Sub

Highlighting mismatched cells using vba

In excel sheet 1 I have a column named phonetype which has some strings in each cell.
I have sheet 2 in the same excel workbook with column name allowed phonetype and some strings in each cell.
Now I want to compare if the strings in Phonetype column of sheet 1 are the same as the strings in allowed phonetype column of sheet 2; If not highlight those cells.
Everything using vba.
Sheet 1 Sheet 2
column name:"Phonetype" columnname:"allowed phone type"
cell 1:welcome cell 1:welcome
cell 2: cell 2:hi121
cell 3:heythere
cell 4:hi121
the string "heythere" is not present in sheet 2(column:"allowed phone type"), so that should be highlighted
Here something to get you started
Option Explicit
'// Campare and Hilight Unique
Sub CompareHighlightUnique()
Dim Range1 As Range
Dim Range2 As Range
Dim i As Integer
Dim j As Integer
Dim isMatch As Boolean
For i = 2 To Sheets("Sheet1").Range("A" & .Rows.Count).End(xlUp).Row
isMatch = False
Set Range1 = Sheets("Sheet1").Range("A" & i)
For j = 1 To Sheets("Sheet2").Range("A" & .Rows.Count).End(xlUp).Row
Set Range2 = Sheets("Sheet2").Range("A" & j)
If StrComp(Trim(Range1.Text), Trim(Range2.Text), vbTextCompare) = 0 Then
isMatch = True
Exit For
End If
Set Range2 = Nothing
Next j
If Not isMatch Then
Range1.Interior.Color = RGB(255, 0, 0)
End If
Set Range1 = Nothing
Next i
End Sub
To change the highlight color edit RGB(255, 0, 0)
to change the sheet1 or sheet2 edit ("Sheet1") and ("Sheet2")
Check it out,,
Sub Button1_Click()
Dim ws As Worksheet, sh As Worksheet
Dim Rws As Long, Rng As Range, a As Range
Dim Rws2 As Long, rng2 As Range, c As Range
Set ws = Sheets("Sheet1")
Set sh = Sheets("Sheet2")
With ws
Rws = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(2, 1), .Cells(Rws, 1))
Rng.Interior.ColorIndex = 6
End With
With sh
Rws2 = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng2 = Range(.Cells(2, 1), .Cells(Rws2, 1))
End With
For Each a In Rng.Cells
For Each c In rng2.Cells
If a = c Then a.Interior.Color = xlNone
Next c
Next a
End Sub
Found here,