I am trying to search for a date in a column in VBA. I have verified that the value exists within the column and I have also formatted the date to be that of the dates in the reference column. Have been scratching my head and i'm not sure what i'm doing wrong. I've seen several questions related to this, and I have even mirrored one of the solutions, which has not worked.
Notes:
1) All dates are stored in column 1 (A) 2) Date format is "m/d/yyyy" 3) Sheet 13 is where the range lives 4) I also have a named range that contains the date i'm searching for and I access that range by referencing the cell rather than the named range since VBA doesn't seem to like that. Any thoughts?
searchString = Format(Sheet3.Cells(5, 4).Value, "m/d/yyyy")
With Sheet13.Range("A:A")
Set searchCell = .Find(What:=CDate(searchString), After:=ActiveCell, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
End With
You need to match the date (stored as number value in Excel):
Dim DateVal As Date
DateVal = Sheet3.Cells(5, 4).Value
With Sheet13.Range("A:A")
Set searchCell = .Find(What:=DateVal, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)
End With
Another example of how using references like ActiveAnything can lead to errors.
In your code, if ActiveCell doesn't happen to be in sheet13 column A, your code will error.
Change to After:=.Cells(1,1) or something similar so you ensure you are starting with some cell within in the column you are using as the SearchRange.
Related
I have a excel serving as timeline record. Column B contains date of a year, and columns right on it record various event.
I want to make a button which can jump to the row of current date. The first thing I try to do is find a cell with specific date in it. I get a date from a existing cell in column B, then turn back to find it. However the Find method returns nothing.
Sub gotoToday()
Dim LDate As Date
Dim dateCol As Range
Dim cell As Range
LDate = Range("b197").Value ' do get a valid date value here
Set dataCol = Range("B2:B365") ' b197 is inside the range
dataCol.Select
Set cell = Selection.Find(what:=LDate, after:=ActiveCell, LookIn:=xlFormulas, _
Lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
cell.Select ' cell get Nothing here
End Sub
Basically I am following This stackoverflow post. Not sure what thing I am missing, can any one help me out?
My guess is that you are looking for a Date type (Dim LDate As Date) whereas dataCol contains strings. Try looking for a string:
Dim LDate As String
'...
LDate = Range("b197").Text
'...
EDIT
You can get a string from a date, formatted to your liking, by using the Format function. Example:
LDate = Format(Range("b197").Value, "mm/dd/yyyy")
If your values in column B really are dates, computed using formulas and formatted as mm/dd, the Find will work with LDate as a string and LookIn:=xlValues, even if they are displayed without the year.
I am trying to set values for variables to be used later on in my code based on the column value of a found cell.
Thanks to some existing subject, I was able to find the cell, but I am unable to set its column value to a name.
Here is my code:
Dim rFind As Range
With Range("A1:DD1")
Set rFind = .Find(What:="FIND", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
MsgBox rFind.Column
End With
End Sub
The MsgBox returns the correct column number but my attempts at getting it set to a name has failed.
Thanks for your help !
EDIT:
My goal is to create an automatic table with data extracted from another table. I want to use the column number to extract data for each row of my table from the correct column. I currently use a system where I "hardcode" my names for the current column number (e.g.: Publi Const example As Integer = 5). However this is not a flexible solution if my data table were to change (new or removed columns). Finding the column to then set it would solve the issue.
Perhaps this, to name the whole column?
rFind.EntireColumn.Name = "Fred"
Fuller code
Sub x()
Dim rFind As Range
With Range("A1:DD1")
Set rFind = .Find(What:="FIND", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
rFind.EntireColumn.Name = "Fred"
Else
msgbox "Not found"
End If
End With
End Sub
I am working with a code to have a user enter in a year, to which excel would then find in a row, and then autofill the formula in that column. I have managed to be able to get the input and column aspect down, but am struggling with how to incorporate my sting into a range. Please help!
Code below.
Sub Copy_formula()
NewPageName = InputBox("Enter in Year")
Dim rFind As Range
Sheets("data_calc").Select
With Range("A2:AH2")
Set rFind = .Find(What:=NewPageName, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
MsgBox rFind.Column
End If
End With
Selection.AutoFill Destination:=Range(Cells(3, "rFind"), Cells(2393, "rFind"))
Range(Cells(3, "rFind"), Cells(2393, "rFind")).Select
End Sub
"rFind" within double quotes is a String which VBA will try to convert to a column number within a Cells() statement. As columns run from "A" to "XFD", anything beyond that should cause an error. So loose the double quotes.
However, that won't entirely solve your problem. The default return for a Range object is its .Value property.
What you want is the Range.Column property.
So change your Range(Cells(3, "rFind"), Cells(2393, "rFind")) to:
Range(Cells(3, rFind.Column), Cells(2393, rFind.Column))
I have the following problem:
I need to highlight period of production order start and finish week, through all columns - as you see in header, there are a lot of production orders.
Is it possible with vba?
Second problem:
Each production line has time capacity, so production minutes should be divided by chosen production line weekly capacity by the end of highlighted period.
This is also need to be done on button click e.g. with vba, or formulas, but I have no idea where to place those formulas, because whole table and header supposed to be dynamic - production plan updates weekly.
UPDATE:
Here's code, that inserts formula in order manufacturing period from start to finish week, i need to loop it through all columns and insert this formula according to following orders start and finish week. And I have no idea how to do that, so help is very appreciated :)
Sub test()
Dim Rng, Rng2, Rng3 As Range
Dim v1, v2 As String
x = Range("E8")
w = Range("E11")
'Search Column or range
With Sheets("forecast").Range("D:D")
Set Rng = .Find(What:=x, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
Set Rng2 = .Find(What:=w, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
'MsgBox Rng.Offset(0, 1).Address
'MsgBox Rng2.Offset(0, 1).Address
v1 = Rng.Offset(0, 1).Address
v2 = Rng2.Offset(0, 1).Address
Range(v1 & ":" & v2).Select
Selection.formula = "=E$12/(E$10-E$7)"
Selection.NumberFormat = "0"
End With
End Sub
Example of production plan:
http://postimg.org/image/3vkx0fv5d/ http://s8.postimg.org/cdud4s1o4/stack3.jpg
As for highlighting you need to put in a "conditional format". (It's on the home ribbon.)
Select the cells from column D11 till the end of the column range needing the formula. Click conditional format and enter the formula:
=AND($B11>D$6;$B11<D$7)
Make sure the dollar marks are in the right spots. And set a format to apply, for example fill to be red. Apply the formula, you just made a conditional format for column D. Now select cell D11 and click "format painter" button and select the whole range to which you want to apply the formula. Done.
update,Adding year:
I only see one year in the sheet. i.e. at the top. So if start/finish week could be of some other year as well that should be added as extra lines start year and finish year. Then create extra lines and columns for the excel date_formats created with help of the formula:
creating excel_date_format
Then you can use the same CF as before now using the newly added column and lines as in:
I am trying to find if a certain date is in a range of dates.
This is the range of dates:
01/01/2013
11/02/2013
29/03/2013
20/05/2013
01/07/2013
05/08/2013
02/09/2013
14/10/2013
11/11/2013
25/12/2013
26/12/2013
Here is the VBA code:
' Format Holiday Rows '
With ConfigData.Range("B8:B18")
Set holidays = .Find(s1.Cells(row_count, 1))
If Not holidays Is Nothing Then
MsgBox s1.Cells(row_count, 1)
End If
End With
In the above code, the first MsgBox that pops up reads "11/01/2013". This makes absolutely no sense, as that value is not in the range.
Note: ConfigData.Range("B8:B18") refers to the range of dates shown above.
ALSO: This code is within a for loop that increments the value of s1.Cells(row_count, 1). Starting at 01/01/2013 until 31/12/2013
If you just want to confirm a calendar day in your series is within the holiday list, then you could even use vlookup:
Dim strFound As String
On Error Resume Next
strFound = Application.Vlookup(s1.Cells(row_count, 1), .Range("B8:B18"), 1, 0)
If IsError(strFound) Then
MsgBox "Not Found"
Else
'-- Found
End If
On Error GoTo 0
The following code works for me:
Sub thing()
Dim cell As Range, _
holidays As Range
For Each cell In Range("D1:D365")
With Range("A1:A11")
Set holidays = .Find(cell.Value, LookIn:=xlValues, lookat:=xlWhole)
If Not holidays Is Nothing Then
Debug.Print cell.Value
End If
End With
Next cell
End Sub
If this doesn't work, I'd suggest it's likely you have a cell formatting issue. Select one of your date cells. Go to the immediate window (Alt+F11, then Ctrl+G from Excel), type ? Selection.Value2 and press enter. Does that return a numeric value (~41000)?
Alternatively, you could reenter the dates in a completely new sheet (enter the first couple manually and drag down, do not copy and paste as formatting will be copied also) and try again. This should at least remove odd formatting as a potential issue.
It is important to note that excel uses american date formatting. ie mm/dd/yyyy and it can therefore be a little tricky to get the .Find() function to work properly. Make sure your variables are formated properly in order for excel to hopefully give you what you're looking for:
Dim strdate As String
Dim aCell As Range
strdate = ActiveSheet.Cells(1,1)
strdate = Format(strdate, "Short Date")
On Error Resume Next
Set aCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlFormulas , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If rCell Is Nothing Then
MsgBox("Date cannot be found. Try Again")
End If
End Sub
Of course there are a lot of annoying things that can happen with the date formatting, but this is assuming the dates you're looking for ar in the "Short Date" format.
'To find a cell elsewhere in a worksheet with the same specific date as a reference cell:
'First copy all dates to cells immediately to their left.
'Format the copied cells as "General"
'Run this code - then use the dateRow and DateCol variables (eg in vlookup)
'Works in Excel 2013 (The "General" column must not be hidden - Hide by formatting in background colour)
Dim dateVal
Dim DateRow
Dim DateCol
dateVal = Range("j8").Value 'must be in general format
Cells.Find(What:=dateVal, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
DateRow = ActiveCell.Row
DateCol = ActiveCell.Column
MsgBox (DateRow & " " & DateCol)
End Sub