Find a range address #2 - excel

So because I wasn't specific with my previous question I need your help again.
Basically, I asked if there's a way to find a range between some value/cells, because I was sure that when i will get that range this below will work (so I can select lets say "headers" of the columns with all the data below:
totalRange(Selection, Selection.End(xlDown)).Select
So one of you came up with help and provide code below, which is working just fine, but i'm not sure if I can use it in my case. Because as I said, what im trying to do is to first find a range between two cells in firstrow and then select all the data below with it. Something like on screenshot below.
I want to find Col7 and Col12 and then select the whole range below.
The problem is this Col7/Col12 range might start from different column in each file.
https://ibb.co/gtuvEb
Sub RangeBetween()
Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long, r2 As Long
r1 = 0
r2 = 0
c1 = 1
c2 = 1
With Worksheets("Sheet1") 'Change to your worksheet
c1 = 1
Do Until Name = "A"
Name = Cells(1, c1)
c1 = c1 + 1
Loop
c1 = c1 - 1
c2 = 1
Do Until Name = "B"
Name = Cells(1, c2)
c2 = c2 + 1
Loop
c2 = c2 - 1
On Error Resume Next
r1 = Application.WorksheetFunction.Match("A", .Columns(c1), 0)
r2 = Application.WorksheetFunction.Match("B", .Columns(c2), 0)
On Error GoTo 0
If r1 > 0 And r2 > 0 Then
Set totalRange = .Range(.Cells(r1, c1), .Cells(r2, c2))
totalRange.Select
Else
MsgBox "One or both items not found in range"
End If
End With
End Sub
Thanks for any suggestions.

Sub RangeBetween()
Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long
With Worksheets("Sheet1") 'Change to your worksheet
On Error Resume Next
'Find the Columns
c1 = Application.WorksheetFunction.Match("Col7", .Rows(1), 0)
c2 = Application.WorksheetFunction.Match("Col12", .Rows(1), 0)
On Error GoTo 0
If c1 > 0 And c2 > 0 Then
'Find last row with data
r1 = .Cells(.Rows.Count, c2).End(xlUp).Row
'Set the range to the whole
Set totalRange = .Range(.Cells(1, c1), .Cells(r1, c2))
totalRange.Select
Else
MsgBox "One or both items not found in range"
End If
End With
End Sub

It seems that you try to look up certain values in the headers and select the ones between those columns. If I understood correctly, your question this can help you.
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("your sheet")
Dim header1 As Range, header2 As Range
On Error Resume Next
Set header1 = ws.Rows(1).Find(what:="your header value 1", LookIn:=xlValues,
lookat:=xlWhole)
Set header2 = ws.Rows(1).Find(what:="your header value 2", LookIn:=xlValues,
lookat:=xlWhole)
On Error GoTo 0
If Not header1 Is Nothing And Not header2 Is Nothing Then
Range(header1,
header2).EntireColumn.SpecialCells(xlCellTypeConstants).Select
Else:
MsgBox "Header not fount"
End If

Related

Trace Dependencies for user defined range and list Source Cell/Dependency Cell in separate sheet

I have a range of cells (user defined) that I want vba to tell me which cell(s) these are linked to.
Every source cell can be linked to 1 or multiple cells.
I have the code so far that it
prompts the user for the range
checks that only 1 row is selected.
counts the amount of cells in the range.
creates a separate sheet to list the dependencies.
I am struggling to have the each source cell listed horizontally and 2 rows below the dependency cell(s).
Option Explicit
Sub ListDependents()
Dim rng As Range
Dim r As Range
Dim cell As Range
Dim n As Long, i As Long
Application.ScreenUpdating = False
'Use InputBox to prompt user for range.
'Test for cancel and a single-cell selection.
Set rng = Application.InputBox( _
Title:="Please select a range", _
Prompt:="Select range", _
Type:=8)
On Error GoTo 0
'Test for cancel.
If rng Is Nothing Then Exit Sub
'Test for single-cell selection.
'Remove comment character if single-cell selection is okay.
If rng.Rows.Count > 1 Then
MsgBox "You’ve selected more than 1 row. Please select contiguous cells per row only."
End If
'rng.Select to confirm selection
MsgBox rng.Address
'count cells to be reviewed for dependencies
For Each cell In rng.Areas
n = n + cell.Cells.Count
Next cell
Sheets.Add().Name = "Dependents"
'add first cell of range in B1, second in C1 etc until end of range
'then add first dependent of first range cell in B3, second in C3 etc
If n > "0" Then
i = 1 + i
Sheets("Depentent Test").Cells(2, i) =
End Sub
Source Sheet
Destination Sheet
Try this. I would suggest replacing my variable names with more useful ones. I haven't included a check that a cell has any dependents which is advisable as otherwise it will probably error.
Sub ListDependents()
Dim rng As Range
Dim r As Range
Dim cell As Range
Dim n As Long, i As Long, j As Long
Application.ScreenUpdating = False
'Use InputBox to prompt user for range.
'Test for cancel and a single-cell selection.
Set rng = Application.InputBox( _
Title:="Please select a range", _
Prompt:="Select range", _
Type:=8)
On Error GoTo 0
'Test for cancel.
If rng Is Nothing Then Exit Sub
'Test for single-cell selection.
'Remove comment character if single-cell selection is okay.
If rng.Rows.Count > 1 Then
MsgBox "You’ve selected more than 1 row. Please select contiguous cells per row only."
End If
'rng.Select to confirm selection
MsgBox rng.Address
Sheets.Add().Name = "Dependents"
'add first cell of range in B1, second in C1 etc until end of range
'then add first dependent of first range cell in B3, second in C3 etc
Dim ra As Range, r1 As Range, r2 As Range
j = 2
For Each ra In rng.Areas
For Each r1 In ra
Cells(1, j) = r1.Address
i = 3
For Each r2 In r1.Dependents
Cells(i, j) = r2.Address
i = i + 1
Next r2
j = j + 1
Next r1
Next ra
End Sub
I found a solution to add the headers above each dependency. I moved the rows down by one to have space for a header and then used offset to match the respective header.
j = 2
For Each ra In rng.Areas
For Each r1 In ra
Cells(2, j) = r1.Address
Cells(1, j) = r1.OffSet(-1, 0).Value
i = 4
For Each r2 In r1.Dependents
Cells(i, j) = r2.Address
Cells(i - 1, j) = r2.OffSet(-1, 0).Value
i = i + 2
Next r2
j = j + 1
Next r1
Next ra

Find a range address

I want to select some range based on cells value, as they might be each time in different column.
So my first thought was something like below, but I'm not sure if that's the right way?
Sub RangeBetween()
Dim rng1 As Range, rng2 As Range
Dim totalRange As Range
Dim c1, c2 As Integer
c1 = 1
Do Until Name = "A"
Name = Cells(1, c1)
c1 = c1 + 1
Loop
someA= c1 - 1
c2 = 1
Do Until Name = "B"
Name = Cells(1, c2)
c2 = c2 + 1
Loop
someB= c2 - 1
Set rng1 = Range("???")
Set rng2 = Range("???")
Set totalRange = Range(rng1.Address & ":" & rng2.Address)
totalRange .Select
End Sub
Thanks
Or you can use Match()
Sub RangeBetween()
Dim totalRange As Range
Dim c1 As Long, c2 As Long
c1 = 0
c2 = 0
With Worksheets("Sheet1") 'Change to your worksheet
On Error Resume Next
c1 = Application.WorksheetFunction.Match("A", .Rows(1), 0)
c2 = Application.WorksheetFunction.Match("B", .Rows(1), 0)
On Error GoTo 0
If c1 > 0 And c2 > 0 Then
Set totalRange = .Range(.Cells(1, c1), .Cells(1, c2))
totalRange.Select
Else
MsgBox "One or both items not found in range"
End If
End With
End Sub

Excel: VBA to copy values to specific row

I currently have a macro that copies the value from a specific cell from one sheet(BACKEND), and pastes in specific column in another sheet (EXPORT_DATA), in the next blank row.
Sub copy_values(Optional Source As String = "A1", Optional Source2 As String = "A1")
Dim R As Range
Dim col As Long
col = Range(Source).Column
Set R = Worksheets("EXPORT_DATA").Cells(Rows.Count, col).End(xlUp)
If Len(R.Value) > 0 Then Set R = R.Offset(1)
R.Value = Worksheets("BACKEND").Range(Source2).Value
End Sub
It works well, but I want to replace the the function in where it pastes the data in the next blank cell in a column, to a function in where it pastes the data in a row in where a cell holds a specified value.
For example, the older function would do the following
step 1:
c1 c2 c3
a b 4
c d 6
step 2 (after macro executed):
c1 c2 c3
a b 4
c d 6
c d 5
But I need a new function that does this:
step 2 (C1 value of "c" specified, macro executed):
c1 c2 c3
a b 4
c d 5
See how this goes for you. Not sure how you are calling etc but it should be a reasonable starting point. I only gave it a really quick test
Sub copy_values_SINGLE(cValue As Variant, Optional Source As String = "A1", Optional Source2 As String = "A1")
' Not sure of what value type c in your question would be but expects a single value to test against the column provided as Source
' Requires cValue to be provided
Dim R As Range
Dim col As Long
Dim destRow As Integer
col = Range(Source).Column
On Error Resume Next
destRow = 0
destRow = Worksheets("EXPORT_DATA").Columns(col).Find(cValue, SearchDirection:=xlPrevious).Row
If destRow = 0 Then destRow = Worksheets("EXPORT_DATA").Cells(Rows.Count, col).End(xlUp).Row + 1 ' if cValue isnt found reverts to the last row as per previous code
On Error GoTo 0
Set R = Worksheets("EXPORT_DATA").Cells(destRow, col)
R.Value = Worksheets("BACKEND").Range(Source2).Value
End Sub
This may work
Sub copy_values(Optional Source As String = "A1", Optional Source2 As String = "A1")
Dim R As Variant
Dim col As Long
col = Range(Source).Column
Dim mrn As String
Dim FoundCell As Excel.Range
Dim myVal As String
R = Worksheets("BACKEND").Range(Source2).Text
myVal = Worksheets("BACKEND").Range(Source2).Text
mrn = Worksheets("BACKEND").Range("A5").Value
Set FoundCell = Worksheets("EXPORT_DATA").Range("A:A").Find(what:=mrn, lookat:=xlWhole, searchdirection:=xlPrevious)
If Not FoundCell Is Nothing Then
' MsgBox (R & " " & col & " " & FoundCell.Row)
Worksheets("EXPORT_DATA").Range("Q" & FoundCell.Row).Value = R
Else
MsgBox "error"
End If
End Sub
Still not 100% certain, but I think this is what you are after. The file loop all values in column A of the EXPORT_DATA file and compared them to the value in cell A1 of the BACKEND worksheet. If it finds the value it replaces the value in column B, if it cannot find the value, it adds it at the end:
Sub copy_values_SINGLE()
Dim R As Range
Dim rowCount As Long
Dim varValue As Variant
rowCount = Application.WorksheetFunction.CountA(Worksheets("EXPORT_DATA").Range("A:A"))
For s = 1 To rowCount
If Worksheets("EXPORT_DATA").Range("A" & s).Value = Worksheets("BACKEND").Range("A1").Value Then
Worksheets("EXPORT_DATA").Range("A" & s & ":B" & s).Value = Worksheets("BACKEND").Range("A1:B1").Value
Exit For
Else
If s = rowCount Then
Set R = Worksheets("EXPORT_DATA").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
R.Value = Worksheets("BACKEND").Range("A1:B1").Value
End If
End If
Next s
End Sub
Let me know if this works for you.

put 0 in a next excel column if previous 4 are empty using VBA

Hi all I am trying to make a vb macro that determins are there 4 empty cells in a row if so it should put 0 in a next row otherwais 1 Here is what I 've done so far
Sub QuickCull()
On Error Resume Next
Columns("a").SpecialCells(xlBlanks).EntireRow.Delete
Columns("b").SpecialCells(xlBlanks).EntireRow.Delete
Columns("d").SpecialCells(xlBlanks).EntireRow.Delete
Dim col As Range
Set col = Cells(Rows.Count, "E").End(xlUp)
Dim r As Range
Set r = Range("E2", col).Resize(, 4)
r.Select
Dim cell As Range
For Each cell In r
If cell.Value = "" Then
cell.Value = 0
Else
cell.Value = 1
End If
Next cell
End Sub
This way I put 0 instad of one blank row I thought about making another cell with a sum of those rows, but is where a way to do it more queckly and productivly?
I think you need something like the following, obviously replace "WORKSHEETNAME" with the name of the worksheet:
Dim r as Range, cell as Range, eRow as Long
eRow = Sheets("WORKSHEETNAME").Cells(Rows.Count, 5).End(xlUp).Row
Set r = Sheets("WORKSHEETNAME").Range("E2:E" & eRow)
For each cell in r.cells
If cell.Offset(0,-4).Value = "" _
And cell.Offset(0,-3).Value = "" _
And cell.Offset(0,-2).Value = "" _
And cell.Offset(0,-1).Value = "" Then
cell.Value = 0
Else
cell.Value = 1
End if
Next cell

Compare two Columns and format matching cells with different colors

I would appreciate your help with the following:
I would like to compare two columns, let us say Column A and Column B, **looking for duplicates**.
If a value in Column A has a match value in Column B, I would like to format the cells of the same duplicate value with the color (the colors are random and different for each match).
This is if `A12 = B30`, the color will be red. And if `A20 = B1`, the color is green and so on.
If there is no match just leave it as it.
That was only an example for red and green. let say you have two columns (A and B).
A1 = 1000
A2 = 2000
A3 = 3000
A4 = 4000
A5 = 5000
A6 = 6000
A7 = 7000
A8 = 8000
A9 = 9000
B1 = 1500
B2 = 9000
B3 = 5000
B4 = 3500
B5 = 7500
B6 = 1000
B7 = 4000
So you have several matches and I need each match to be in random different colors. For example:
A1 = B6 –> They will be colored/highlighted in green
A4 = B7 –> They will be colored/highlighted in red
A5 = B3 –> They will be colored/highlighted in yellow
A9 = B2 –> They will be colored/highlighted in pink
The colors will be different for any match and the non-match will be color less or no change.
I wish this will explain the question and this has to be using excel.
{
Sub UsingCollection()
Dim cUnique As Collection
Dim Rng As Range
Dim Cell As Range
Dim sh As Worksheet
Dim vNum As Variant for at
Dim LstRw As Long
Dim c As Range, clr As Long, x
Set sh = ActiveSheet
With sh
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Rng = .Range("A1:B" & LstRw)
Set cUnique = New Collection
Rng.Interior.ColorIndex = xlNone
clr = 3
On Error Resume Next
For Each Cell In Rng.Cells
cUnique.Add Cell.Value, CStr(Cell.Value)
Next Cell
On Error GoTo 0
For Each vNum In cUnique
For Each c In Rng.Cells
If c = vNum Then
x = Application.WorksheetFunction.CountIf(Rng, vNum)
If x > 1 Then c.Interior.ColorIndex = clr "error here: the code runs fine for around 50 lines then it is stoppedand gives error and pointing to this line"
//Error shows in pop window: Run-time error 'g': Subscript out of range
End If
Next c
clr = clr + 1
Next vNum
End With
End Sub
}
This is an adjusted code from my answer here.
https://stackoverflow.com/a/33798531/1392235
Loop through the cells to find the unique values, then loop through the unique values to color the duplicates.
Sub UsingCollection()
Dim cUnique As Collection
Dim Rng As Range
Dim Cell As Range
Dim sh As Worksheet
Dim vNum As Variant
Dim LstRw As Long
Dim c As Range, clr As Long, x
Set sh = ActiveSheet
With sh
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
Set Rng = .Range("A1:B" & LstRw)
Set cUnique = New Collection
Rng.Interior.ColorIndex = xlNone
clr = 3
On Error Resume Next
For Each Cell In Rng.Cells
cUnique.Add Cell.Value, CStr(Cell.Value)
Next Cell
On Error GoTo 0
For Each vNum In cUnique
For Each c In Rng.Cells
If c = vNum Then
x = Application.WorksheetFunction.CountIf(Rng, vNum)
If x > 1 Then c.Interior.ColorIndex = clr
End If
Next c
clr = clr + 1
Next vNum
End With
End Sub
Results
Sample Workbook
EDIT:
Using colorindex limits us to 56 colors, if we use RGB we can increase that. Edit this part of the code, you will have to play with the values get the color variances you like.
If x > 1 Then c.Interior.Color = 1000000 + clr * 100
End If
Next c
clr = clr + 255

Resources