Trying to search for the cell location of a certain date.
I have a range of dates in dd-mm-yy form and need to be able to find the cell location of a date picked from a drop down menu. I was using a standard Range.Find function which works for searching for Non-dates but when searching for dates it returns error 91: Object variable or With block variable not set.
I have tried converting the dates to text format through both format cells and a =text function in excel prior to running the program but it still does not work.
I read somewhere about converting the date to match the internal format used by Excel (mm/dd/yy) but this didn't make a difference.
'Date to be searched
Set SDate = Sheets("Data").Range("F1")
'find function
Set oRange = Sheets("Planning").Range("A1:A50").Find(What:=Sdate, lookat:=xlWhole)
'Return Address
MsgBox oRange.Address
I expect to be able to search for a cell location and be given a cell location, in either A1 form or (1,1). Both will work.
You have merged cells, that's why it returns Nothing, try:
Sub finddate()
Set Sdate = Sheets("Data").Range("F1")
Set SearchRange = Sheets("Planning").Range("A1:A50")
If Not IsError(Application.Match(Sdate, SearchRange, 0)) Then
Set oRange = Cells(Application.Match(Sdate, SearchRange, 0), 1)
MsgBox oRange.Address
End If
End Sub
Another way to do it:
Sub findDate()
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("The name of your Worksheet")
Dim dateToFind As Date
dateToFind = sht.Range("F1").Value
Dim cell As Range
For Each cell In sht.Range("datesRng").Cells 'I am using a named range which contains the dates but you can use A1:A50 instead
If cell.Value = dateToFind Then
MsgBox cell.Address
End If
Next cell
End Sub
Combining .Find with date values is a tad tricky, as you found out yourself.
Try the following
Sub finddate()
'Date to be searched
Set SDate = Sheets("Data").Range("F1")
'find function
Set oRange = Sheets("Planning").Range("A1:A50").Find(What:=DateValue(Sdate), lookin:=xlFormulas)
'Return Address
MsgBox oRange.Address
End Sub
Related
I have a long list of equipment like this;
I would like to be able to run a VBA script that allows excel to change the format of the first of a series so that they are more visible. Is this a possibility?
This is housed in an excel table, not sure if that has an impact.
You could iterate through the range update format if below cell<>previous cell.
Sub UpdateCatHead(ByRef rng As Range, Optional col_index As Integer = 1)
Dim rng_search As Range
'lets ,make sure to have range of one column
Set rng_search = rng.Columns(col_index)
Dim cell As Range, prev_cell As Range
Dim prev_cat As String
For Each cell In rng_search.Cells
'check if empty is empty and exit for?
If cell.Row = 1 Then
'update cell to bold here
Debug.Print (cell.Row)
Else
Set prev_cell = cell.Worksheet.Cells(cell.Row - 1, cell.Column) 'cell above
If CStr(cell.Value) <> CStr(prev_cell.Value) Then
'update cell to bold here
Debug.Print (cell.Row)
End If
End If
Next cell
End Sub
call Sub like this:
UpdateCatHead ThisWorkbook.Sheets("data").Range("A1:A100")
Im trying to make a VBA in excel that changes the content of a cell based on the text in the cells. All the cells I want to change contains a structure of "< (space) 0.005" the number however varies a lot and setting up all the different numbers would take too long.
I have a base for an older project but I can't seem to tweak it to the required needs.
Sub FillEmptyBlankCellWithValue()
Dim cell As Range
Dim InputValue As String
On Error Resume Next
InputValue = InputBox("Enter value that will fill empty cells in selection", _
"Fill Empty Cells")
For Each cell In Selection
If IsEmpty(cell) Then
cell.Value = InputValue
End If
Next
End Sub
You're on a right track. But in general I'd avoid using Selection or any other Select operations as they are prone to many errors.
Instead, I'd recommend using active (detected dynamic) range, or let the user define the range. eg.
Option Explicit
Private Sub fill_blanks
Dim ws as Worksheet: Set ws = Sheets("Sheet1") ' set yours
Dim firstcell as String, lastcell as String, fillvalue as String
Dim datarange as Range
firstcell = InputBox("Enter the starting cell of your data range")
lastcell = InputBox("Enter the last cell of your data range")
fillvalue = InputBox("Enter the value to fill blank cells with")
Set datarange = ws.Range(Trim(firstcell) & ":" & Trim(lastcell))
Dim cell as Range
For each cell in datarange
If IsEmpty(cell) Then
cell = fillvalue
End If
Next cell
End Sub
You could also let them define the range inside a pre-defined cells in
the worksheet, or detect the active range with .End(xlUp) for row
and .End(xlToLeft) for column. Up to you really..
Note: This will paste the result as a String (or "Text") as a Cell Format, you also need to change the Range.Format property.
I am trying to produce a VBA function that will hide all columns for which cells D9:CC9 are not equal to "A6" and cells D8:CC8 are not equal to "12." Based on the script below, the system keeps returning an error. I am new to VBA, was hoping someone might be able to assist.
Thanks!
Dim MyCell As Range
Set MyCell = Range("D9:CC9,D8:CC8")
For Each cell In MyCell
If cell.Value <> WorksheetFunction.Index(Range("D9:CC9"),WorksheetFunction.Match(Range("A6")&"12",Range("D9:CC9")&Range("D8:CC8"), 0))
cell.EntireColumn.Hidden = True
End If
Next cell
Most operations are performed quite different using VBA than doing them manually. If you want to work with VBA then should do some research about working with variables and objects. This pages should be of interest.
Variables & Constants, Excel Objects, With Statement & Range Properties (Excel)
I have done some changes to your code, see comments within, and refer to the pages mentioned above.
Sub Rng_HideColumns()
Dim rTrg As Range, rCol As Range
Dim sCllVal As String
Rem Set rTrg = ThisWorkbook.Sheets("Sht(0)").Range("D9:CC9,D8:CC8")
Rem Refers to the worksheet you want to work with instead or using the active worksheet
With ThisWorkbook.Sheets("Sht(0)")
Rem Get value to match
sCllVal = .Range("A6").Value2 & 12
Rem Set Range to Search
Set rTrg = .Range("D8:CC9")
For Each rCol In rTrg.Columns
With rCol
If .Cells(2).Value2 & .Cells(1).Value2 = sCllVal Then
.EntireColumn.Hidden = 1
Else
.EntireColumn.Hidden = 0
End If: End With: Next: End With
End Sub
Im a beginner with Excel VBA
my question is if I have string in a cell like "MyNameIsHammadAndImFromIreland".
All cells have strings/sentences but there is no spaces.
How can I find if the cell includes the word "Ireland"?
The following VBA code will iterate through the used cells in a given worksheet and find any that match the given criteria. At the end, a message box is displayed showing a list of cells that contain the search term.
This functionality is equivalent to using the 'Find All' option you can choose when you use the normal find functionality available by pressing CTRL + F.
Option Explicit
Private Sub Find()
Dim rngResult As Range
Dim strToFind As String
'Set to your desired string to find
strToFind = "Ireland"
'If the string you are searching for is located in
'the worksheet somewhere, you can set the value
'like this: strToFind = Worksheets("Sheet1").Range("A1").Value
'This assumes your search term is in cell A1 of the
'Sheet1 worksheet.
'Look in the used range of a given worksheet
'Change Sheet1 to match your worksheet name
With Worksheets("Sheet1").UsedRange
'Find the first cell that contains the search term
Set rngResult = .Find(What:=strToFind, LookAt:=xlPart)
'If it is found, grab the cell address of where the
'search term can be found
If Not rngResult Is Nothing Then
Dim firstAddress As String, result As String
firstAddress = rngResult.Address
'Loop through the rest of the cells until returning
'to the first cell that we had a match in.
Do
'Record the cell address of the match
'to the result string
result = result & rngResult.Address & ","
'Go to next cell containing the search term
Set rngResult = .FindNext(rngResult)
'Exit the loop when we reach the starting point
Loop While rngResult.Address <> firstAddress
'Output the list of cells that contain the string to find
MsgBox "Found """ & strToFind & """ in cell(s): " & result
End If
End With
End Sub
Be sure to set strToFind to your desired string, and change Sheet1 to match the name of whichever sheet you want to search over.
You don't need VBA, just use a formula:
=IF(LEN(SUBSTITUTE(A1,"Ireland",""))<LEN(A1),"Word Found","Word NOT found")
If you really want VBA then:
hasWord = InStr(Range("A1").Value, "Ireland") > 0 '// returns TRUE or FALSE
I am working on a spreadsheet that will take a list of dates, and find those dates on a different sheet and populate some info in the cell below the matching date. The data to search through looks something like this:
ROW23: dates generated by formula (formatted: d-mmm)
ROW24: Mix of empty cells and cells with text and numbers.
ROW25: dates generated by formula (formatted: d-mmm)
ROW26: Mix of empty cells and cells with text and numbers.
and so on
This range is called "Calendar" and is Sheet9(B23:O74).
This list of dates to search are "List_Holidays" and is Sheet5(B9:B12,B16:B21). Once the date is located, the text to return in the cell below it is "List_HolAbbr" on Sheet5(A9:A12,A16:A21).
Currently I'm stuck on stage 1 of this code: Get it to run looking for only one date.
Stage 2 is to have it search for a list of dates.
Stage 3 is to have it only search through the rows that actually contain dates from the example above (skip the row of empty cells and cells with text/#s.
Stage 4: Have it populate the cell under the found date with some text.
My attempt so far:
Sub holidays()
Dim Cal As Range
Dim vholidays As Long
Dim cl As Range
Dim clgcaldate As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
'Find this
Set rgholidays = Worksheets("Holidays_EndPeriods").Range("F10") 'This is the date of the holiday to find in range Calendar
vholidays = DateValue(rgholidays)
MsgBox "vholidays is " & vholidays
'Search this range
MsgBox "g47 is: " & Sheets("2015_Consolidated").Cells(47, "G") 'G47 is the match to the cell in "rgholidays".
For Each cl In Cal
'With Range("List_Holidays)
Set rFound = Cells.Find(what:=vholidays, _
LookIn:=xlValues, _
lookat:=xlWhole, _
SearchOrder:=xlByRows) 'The cell in range Calendar that matches to vholidays
'Match found
If Not rFound Is Nothing Then
MsgBox "rFound is " & rFound
End If
'End With
Next cl
MsgBox "vholidays is " & vholidays & " and is located: " & rFound
End Sub`
The first 2 msgboxs are correct, but it does not find the match in G47.
I also tried this code, found at: Excel VBA - Using Find method on a range of dates
Second try, using the same variables as above.
`MsgBox "vhol is " & vholidays & " rghol is " & rgholidays
For Each cl In Cal
With rgholidays
Set rFound = .Find(vholidays, LookIn:=xlValues, lookat:=xlWhole)
If Not rFound Is Nothing Then
MsgBox cell
End If
End With
Next cl
End Sub`
Again, this does not return a match.
http://www.cpearson.com/excel/DateTimeVBA.htm recommends using DateValue() to convert the dates to a serial number, which seems reasonable to me and i tried it in the first example.
I've found some other references, but those are further removed from I'm trying to do.
Any suggestions to make this work?
Edit: I set a condition to test if the formats were the same for the search value and the value it should find. It said they were the same.
Testing the find/replace gui box on the spreadsheet, "find" does not locate the proper cell regardless of the find/replace settings.
Edit: I tried Application.Match. No match found. This loops through each column in the range looking for a match to the date, but doesn't find anything.
Sub holidays()
Dim Calendar As Range
Dim cl As Range
Dim rFound As Variant
Dim findthis As Double
Dim rng As Range
Dim Cal As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
findthis = CDate(CLng(Sheets("2015_Consolidated").Range("K17"))) '"1/13/2015"
Debug.Print "find this:" & findthis
Debug.Print "cell d23: " & ActiveSheet.Cells(23, 4)
For Each rng In Range("Calendar").Columns
Debug.Print rng.Address
rFound = Application.Match(findthis, rng.Address, 0)
If IsError(rFound) Then
Debug.Print "Not found"
Else
Debug.Print rFound
End If
Next rng
End Sub
Afer you set "Cal" and "rgholidays" variables in your code, try:
For each cell in Cal
if format(rgholidays,"m/d/yyyy")=format(cell,"m/d/yyyy") then
'Cell has the same date, do some code
endif
Next cell
When working with dates, another way to work with them is to format them yyyymmdd, then the larger numbers are always later then smaller ones, for example. This should get stage 1 of your question, to find the dates. Stage 2 and 4 should be some version of this code, combined with something you write. Stage 3 might be tricky, unless your line of non-dates is always constant.