How to get the value from a cell on an active sheet and look it up on a non active sheet and then rename the value?
Dim rw As Long
rw = ActiveCell.Row
If Sheets("Home").Range("D" & rw).Value = "Tender" Then
With Worksheets("Time Allocation").Columns("B:B")
Set cell = .Find(What:=.Range("B" & rw).Value, After:=Range("B" & rw), LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not cell Is Nothing Then
cell.Value = "test"
Else
cell.Value = "test"
End If
End With
End If
I have tried using cell.value = "test" but this causes an error:
object variable or block with variable not set
please can someone show me where I am going wrong?
The bad news is that you cannot .Select one or more cells on an inactive worksheet. The good news is that there is absolutely no requirement that you do so and in fact it is generally less efficient than directly addressing the cell, cells or column(s).
Dim rw As Long, cell as range
rw = ActiveCell.Row
If Sheets("Sheet1").Range("D" & rw).Value = "Tender" Then
With Worksheets("Sheet2").Columns("B:B")
Set cell = .Find(What:=Sheets("Sheet1").Range("B" & rw).Value, LookIn:=xlFormulas, _
LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not cell Is Nothing Then
cell = "test" '<~~the default property is the .Value
Else
MsgBox "cannot test. not found. cell is nothing and cannot be referenced."
End If
End With
End If
The way you are bouncing around between two worksheets and referring to the ActiveCell property like it is on one worksheet sometimes and another worksheet other times is a little confusing. I'm not sute I got the What parameter right in the Range.Find method.
See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.
Related
On an excel sheet, there are some continuous ranges with the same color in a row. The problem is to find all these continuous ranges not as individual cells but as a set of continuous ranges.
Tried cell.displayformat.interior.color but getting continuous ranges is the problem.
For the below image, we need to get the 3 continuous ranges with the same color.
You could use the Union function to do the heavy lifting - it automatically creates the areas as you add cells to it. So you could iterate a Find, looking for the cell colour, and add it to a found collection of cells with Union.
In your example, this would give you three areas. Skeleton code would be:
Dim cell As Range, foundRange As Range, colouredArea As Range
Dim firstAddr As String
With Application.FindFormat
.Clear
.Interior.Color = 10921638
End With
Set cell = Sheet1.Range("A1")
Do While True
Set cell = Sheet1.Cells.Find( _
What:="", _
After:=cell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=True)
If cell Is Nothing Then Exit Do
If cell.Address = firstAddr Then Exit Do
If firstAddr = "" Then firstAddr = cell.Address
If foundRange Is Nothing Then
Set foundRange = cell
Else
Set foundRange = Union(foundRange, cell)
End If
Loop
If Not foundRange Is Nothing Then
For Each colouredArea In foundRange.Areas
Debug.Print colouredArea.Address
Next
End If
I'm trying to get a VBA code together that can take the date from cell B5 on one sheet and locate the exact match from a column on a different sheet, then select that as the active cell. any ideas?
Heres what i've tried;
Sub find()
Sheets("Details").Select
Range("B5").Select
rngY = ActiveCell.Value
Sheets("Calcs").Select
Columns("C:C").Select
Selection.find(What:=rngY, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Select
End Sub
Something like this should work for you:
Public Sub FindInSheet2()
Dim r As Range, lookupVal As Variant
lookupVal = ThisWorkbook.Worksheets("Details").Range("B5").Value
Set r = ThisWorkbook.Worksheets("Calcs").Range("C:C").Find(What:=lookupVal, LookAt:=xlWhole, LookIn:=xlValues)
If Not r Is Nothing Then
ThisWorkbook.Worksheets("Calcs").Activate
r.Select
Else
MsgBox "Lookup not found", vbOKOnly
End If
End Sub
The main difference between this code and yours is that I haven't relied on ActiveCell or Selection. It's better to be specific about which ranges you are working with. For more info, see How to avoid using Select in Excel VBA
I want to implement a VBA Code to work with multiple different sheets, for example: it starts by looking for a certain number in the first row, once it's found, it jumps to that column and types a certain formula into the 2nd cell in that column, so far it works good, But the issue is that I wanna make it to Autofill that formula down the column if the first cell in that row contains data.
Like if A2 is not blank, continue the auto fill the cell in the active column (let's say the active column is D, then the it would fill the Cell d2 if a2 not blank) and stops once the cell in A Column is blank .. etc
So, Is it possible?
Sub Macro1()
Rows("1:1").Select
Selection.Find(What:="156", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
ActiveCell.Offset(1).Select
ActiveCell.FormulaR1C1 = _
"= "Formula will be here""
End Sub
Might be best to save a copy of your workbook before running the code below.
Maybe something like this is what you're after. If Find found something in column D, then it puts the dummy formula in the range D2:D?, where ? is whatever the last row in column A is (which I think is what you described).
Option Explicit
Sub Macro1()
Dim ws As Worksheet
Set ws = ActiveSheet ' Can you refer to the workbook and worksheet by name? Please do if possible
With ws
Dim cellFound As Range
Set cellFound = .Rows(1).Find(What:="156", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True, SearchFormat:=False)
If cellFound Is Nothing Then
MsgBox ("The value was not found in the first row of sheet '" & ws.Name & "'. Code will stop running now")
Exit Sub
End If
Dim lastRow As Long
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range(cellFound.Offset(1), .Cells(lastRow, cellFound.Column)).FormulaR1C1 = "=""Formula will be here"""
End With
End Sub
Check this simple code, I think it will satisfy your needs:
Sub Macro1()
Rows("1:1").Select
Selection.Find(What:="156", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
col_Num = ActiveCell.Column
total_Rows = WorksheetFunction.CountA(Range("A:A"))
Cells(2, col_Num).Select
Cells(2, col_Num) = "=Put your Formula here"
begin_Cell = Cells(2, col_Num).Address(False, False)
end_Cell = Cells(total_Rows, col_Num).Address(False, False)
Selection.AutoFill Destination:=Range(begin_Cell & ":" & end_Cell)
End Sub
There are easier ways to locate a column header label although I'm unclear on why you are using the LookAt:=xlPart argument. It seems to me you should not have to 'wildcard' the search but a 'wild card' search can be accommodated.
Sub FindnFill()
dim m as variant
with worksheets("sheet1")
m = application.match("*156*", .rows(1), 0)
if not iserror(m) then
if not isempty(.cells(2, "A")) then
.range(.cells(2, m), .cells(.rows.count, "A").end(xlup).offset(0, m-1)).formula = _
"=""formula goes here"""
else
.cells(2, m).formula = _
"=""formula goes here"""
end if
end if
end with
end sub
Find & Fill
About the Find Method
It is best practice to always set the following three parameters, because they
are saved each time they are used.
LookIn - If you use xlFormulas, it will find e.g. =A2 + 156, which you don't want.
LookAt - If you use xlPart it will find e.g. 1567, which you don't want.
SearchOrder - Not important, since a row is being searched.
Additionally SearchDirection is by default xlNext and can therefore safely be omitted.
Additionally MatchCase is by default False and can therefore safely be omitted.
Additionally SearchFormat - To use it you previously have to set Application.FindFormat.NumberFormat and can therefore safely be omitted.
The Code
Sub FindFill()
Const cDblFind As Double = 156 ' Found Value
Const cLngRow As Long = 1 ' Found Row Number
Const cVntColumn As Variant = "A" ' First Column Letter/Number
Const cStrFormula As String = "=RC[-1]+5" ' Formula
Dim objFound As Range ' Found Column Cell Range
Dim lngRow As Long ' First Column Non-empty Rows
With ActiveSheet.Rows(cLngRow)
' Check if cell below cell in First Column and Found Row is empty.
If .Parent.Cells(cLngRow, cVntColumn).Offset(1, 0).Value = "" Then Exit Sub
' Calculate First Column Non-empty Rows.
lngRow = .Parent.Cells(cLngRow, cVntColumn).End(xlDown).Row - cLngRow
' Find cell in Found Row containing Found Value.
Set objFound = .Find(What:=cDblFind, After:=.Cells(.Row, .Columns.Count), _
LookIn:=xlValues, LookAt:=xlWhole, Searchorder:=xlByRows)
If Not objFound Is Nothing Then
' Write Formula to Found Column Range
objFound.Offset(1, 0).Resize(lngRow).FormulaR1C1 = cStrFormula
End If
End With
End Sub
Newbie here need help to find the next emptycell in a range from the activecell.row....
Sub FindNextCell()
'
'Macro1 Macro
Cells.Find(What:="", _
After:=Range("F2:I22")(Cells(ActiveCell.Row, _
Columns.Count).End(xlToLeft).Offset(0, 1)), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False).Activate
End Sub
When using the Find method, it's better to set the result as a Range.
Of course, there is a possibilty the Find will not return any results (in case it doesn't find another empty cell in the specifed range), that's why we add If Not EmptyRng Is Nothing Then.
Code
Option Explicit
Sub FindNextCell()
Dim FindRng As Range, EmptyRng As Range
' define the Range to search according to ActiveCell current row
Set FindRng = Range("F" & ActiveCell.Row & ":I" & ActiveCell.Row)
' COMMENT : need to cheat a little to get the first cell founds in the searched range
' by starting from the last column in the range, Column "I"
' Otherwise, will return the second cell found in the searched range
Set EmptyRng = FindRng.Find(What:="", after:=Cells(ActiveCell.Row, "I"), _
LookIn:=xlValues, lookat:=xlWhole)
' found an empty cell in the specified range
If Not EmptyRng Is Nothing Then
EmptyRng.Select
Else ' unable to find an empty cell in the specified range
MsgBox "Unable to find an empty cell in " & FindRng.Address & " Range"
End If
End Sub
I am trying to write a macro in excel sheet. In this macro, do I take a copy of the cell number (B04) and I search on the worksheet (3), but the problem that I am having is when I want to change the content of the cell macro is also searching for new content
Range("D6").Select
Selection.Copy
Sheets("3").Select
Cells.Find(What:="Yasser Arafat Ateya ELsayed EL", After:=ActiveCell, _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Range("B6").Select
Application.CutCopyMode = False
Selection.ShowDetail = True
End Sub
Going with the flow of your code, and with a bit of explanation to help you, amend your code to something like this. Also learn about explicitly referencing separate worksheets in your code rather than relying on ActiveSheet.
Sub findSomeText()
'the find method returns a Range so define a variable to catch this
Dim fndrng As Range
'to search for different strings use a String variable
Dim srchStr As String
'get the srchStr (in this case from D6 in the ActiveSheet)
srchStr = ActiveSheet.Range("D6").Value
'use Sheets("3") - you don't need to select it
'note that this means a Sheet with a (Tab)NAME of "3", not necessarily the third sheet
With Sheets("3")
'explicitly set the ActiveCell to Find from
Range("A1").Activate
'apply the Find method, note use LookIn:=xlValues; use of srchStr and .Cells
Set fndrng = .Cells.Find(What:=srchStr, After:=ActiveCell, _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
'check if a match has been found
If Not fndrng Is Nothing Then
'your code if srchStr has been found goes here e.g. found value into cell B6
Range("B6").Value = fndrng.Value
' perhaps use MsgBox "Found" to test?
Else
'your code if srchStr has NOT been found goes here
MsgBox "Not Found"
End If
End Sub