I have a set of dates in column B like 06/03/2017 formatted in a custom dd-mmm formatting giving me 06-Mar output.
If I manually do Find/Replace and search for 06-Mar and select Look In: Values, it finds it no problem, however doing the same via VBA isn't working.
Dim Source as Worksheet, Dest as Worksheet
Dim mDate as String, copyRow as Integer
Set Dest = ThisWorkbook.Sheets("Weekly Updates")
Set Source = ActiveWorkbook.Sheets("Weekly Updates")
mDate = Dest.Range("B2").Text
copyRow = Source.Range("B:B").Find(What:=mDate, LookIn:=xlValues).Row
I have tried getting mDate as a value and searching in formulas and values, but nothing seems to work.
The line debugs on copyRow = Source....... however if I open the Find/Replace window manually at this point, it fills out the search bar with "06-Mar", and finds the value in column B no issues.
If I replace mDate with string I know is there, for example Find(What:="W/C"..... it returns copyRow as 1 (because its the header of that column).
Any suggestions what I am missing here?
EDIT
To cover a few of the comments below:
Yes the sheets are named the same, just in different workbooks (master file to pull data from multiple identical sources)
In terms of the formatting, I get the search criteria from a date with a true value of 06/03/2017 formatted as dd-mmm, searching in a range of data as true dates 06/03/2017 formatted also as dd-mmm.
Try to give the variable mDate the same format of your date :
copyRow = Source.Range("B:B").Find(What:=Format(mDate, "dd-mmm"), LookIn:=xlValues).Row
Related
EDIT: Short version (longer explanation below):
I have a variable date value in Sheet8.Range("s1")
I have a named range in Sheet3 called "HolidaySchedule"
I am trying to use the variable date from Sheet8 to find the corresponding column of the date in "HolidaySchedule" where dates are listed in one row.
I'm trying to get the column number in "HolidaySchedule" where the variable date appears stored in a value (e.g. Dim iTargetCol as Integer)
Sub Scheduler()
'The below code sample correctly grabs the date value (e.g. 21/08/2019) and correctly references the named range location
Dim vCurrentDate As Variant
Dim rCurrentDateCol As Range
Dim lCurrentDateCol As Long
Dim iTargetCol As Integer
Dim rRng As Range
vCurrentDate = Sheet8.Range("s1").Value
Set rRng = Sheet3.Range("HolidaySchedule")
Long version:
Our team uses Excel sheets to allocate work schedules. I'm trying to create some VBA code so that it automatically creates a work schedule for our team based on a date entered in a different sheet.
I'm new to VBA and trying to use the find method to locate the date of one sheet to the corresponding date in a named range of a different sheet. I can't seem to get VBA to allow me to use the .Find to locate the date in the named range. Ideally, I'm able to locate the column number of the date from the different sheet that's located in the named range (example code below)
Sheet8 includes a date listed in cell S1
Sheet3 includes a list of dates for the corresponding month of the date listed in cell S1
The named range of Sheet3 called "HolidaySchedule" (C5:AJ9) has the dates listed horizontally across row 5 (but this may change): namely F5:AJ5 (the first few columns are for the names/position/etc)
The dates in F5:AJ5 are calculated using the first day of the month and each corresponding cell to the right is just the value of the cell to the left +1 (for instance: the formula in Cell G5 is F5+1)
The dates in F5:AJ5 are listed in Chinese text corresponding to the month and the date (e.g. 8月5日 which translates to 8th Month 5th Day = Aug 5)
For example purposes, Cell s1 in Sheet8 has the value of 21/8/2019.
Sheet3 F5:AJ5 has Aug 1 in cell F5 (actual text: 8月1日), Aug 2 in cell F5 (actual text: 8月2日).
I'm quite proficient in using "regular" excel coding language and have tried to use a similar Application.Match in VBA to find the column number of the corresponding date in the named range, but that doesn't seem to be working as well.
I've tried on stackoverflow to find similar problems with finding dates in ranges of cells that contain dates but their solutions don't seem to work for me for some reason.
I've also taken a look at the Excel help on how the find function accepts its different parameters but can't seem to get it to work.
I originally thought that the cells in Sheet3 F5:AJ5 were not properly formed as values but if I copied and pasted the values into a blank row, they appropriately show up as 43678, 43679, 43680, etc
Sub Scheduler()
Dim vCurrentDate As Variant
Dim rCurrentDateCol As Range
Dim lCurrentDateCol As Long
Dim iTargetCol As Integer
Dim rRng As Range
vCurrentDate = Sheet8.Range("s1").Value
Set rRng = Sheet3.Range("HolidaySchedule")
'NOTE - Only 1 of either attempt a) or attempt b) or attempt c is active at a time. If a is active, the code for attempt b and attempt c is commented out
Attempt :
using Application.Match to find the date in the named range
lCurrentDateCol = Application.Match(CLng(CDate(vCurrentDate)), rRng, 0)
using the .Find method after looking on Stackoverflow
'Note I've also tried ThisWorkbook.Sheet3.Range(rRng).Find(.......)
Set rCurrentDateCol = rRng.Find(what:=CDate(vCurrentDate), LookIn:=xlFormulas, lookat:=xlWhole)
If Not rCurrentDateCol Is Nothing Then
iTargetCol = rCurrentDateCol.Column
End If
Message iTargetCol
using the .Find method after looking on Stackoverflow
Dim cell as Range
For Each cell In rRng
Set rCurrentDateCol = rRng.Find(what:=CDate(vCurrentDate), LookIn:=xlFormulas, lookat:=xlWhole)
If Not rCurrentDateCol Is Nothing Then
iTargetCol = rCurrentDateCol.Column
Exit For
End If
Next
MsgBox iTargetCol
End Sub
Expected: return column number within the named range once it finds the date from the other sheet in this named range (i.e. supposed to return 24)
e.g.
21/8/2019 as Sheet 8.Range("s1").value;
In Sheet 3
Cell F5 contains value of 43678 (equiv to Aug 1, 2019 formatted as "8月1日")
Cell G5 contains value of 43679 (equiv to Aug 2, 2019 formatted as "8月2日")
...
Cell Z5 contains value of 43698 (equiv to Aug 21, 2019 formatted as "8月21日")
Actual results if using attempt a:
Run-time error '13': Type mismatch
Actual results if using attempt b and c:
Msgbox "Not found"
Like this?
Sub Scheduler()
vCurrentDate = Sheets("Sheet3").Range("A2").Value
Set rRng = Sheets("Sheet3").Range("HolidaySchedule")
lCurrentDateCol = Application.Match(vCurrentDate * 1, rRng, 0)
Sheets("Sheet3").Range("C2").Value = lCurrentDateCol
End Sub
EDIT:
If you have trouble with the variable types, either delete them altogether (and don't forget to delete "option explicit" at the start of your code. Or set them like this:
Sub Scheduler()
Dim vCurrentDate As Long
Dim rCurrentDateCol As Range
Dim lCurrentDateCol As Long
Dim iTargetCol As Integer
Dim rRng As Range
vCurrentDate = 1 * (Sheets("Sheet3").Range("A2").Value)
Set rRng = Sheets("Sheet3").Range("HolidaySchedule")
lCurrentDateCol = Application.Match(vCurrentDate, Range(rRng.Address), 0)
Sheets("Sheet3").Range("C2").Value = lCurrentDateCol
End Sub
I'm trying to write a code that would look up a string value (that I would get from the user) from a table located in another sheet of my workbook.
I've tried using the Range.Find function as well as Application.WorksheetFunction.Vlookup.
Sub ID_Lookup()
Dim name As Variant
Dim FoundID As Range
Dim test_tbl As ListObject
Set test_tbl = Sheets("Sheet1").ListObjects("Full_List")
name = InputBox("Enter ID name:")
'Snippet used to find user input value above located in table from another sheet.
On Error Resume Next
FoundID = test_tbl.DataBodyRange.Find(name, LookAt:=xlWhole)
' FoundID = Application.WorksheetFunction.VLookup(name, test_tbl .DataBodyRange, 1, False)
On Error GoTo 0
End Sub
While the logic above seems to work well for numerical values, it returns an error (in case of Vlookup) and Null (in case of Range.Find) while trying to find string values.
The string values I need to lookup are sometimes a combination of letters, numbers and a period character (for example: AB.CDE2) and I have tried setting the user input to both String and Variant datatypes to no avail. The column from where I would search is also Text ('General' format in Excel).
Any direction would be helpful.
I have encountered a strange problem that I simply cannot get my head around. I have a .csv file which contains 4 columns of dates. As a daily task I have to work with these dates and convert them to DMY format using the TextToColumn option of Excel. The original format of the dates is MDY - and for reasons I don't understand when done manually with Data>Text to Columns>Fixed Width>Date:MDY these dates are converted to correct DMY format.
Here is a screenshot of the raw data in the .csv file:
Raw data
Now I wanted to automate it through a simple macro, and after recording the text to columns operation and doing some tweaking to span all 4 columns I have got the following code:
Sub Text_To_Column()
'
' Select_Column_Get_Length Macro
'
Worksheets("Outcome extract").Activate
Dim l As range
Set l = range("A2", range("A2").End(xlDown))
Dim h As Long
h = l.Count
Dim daterange As range
Dim firstcell As range
Set firstcell = range("FG2")
Set daterange = range(firstcell, firstcell.Offset(0, 3))
For Each n In daterange
Dim dates As range
Set dates = range(n, n.Offset(h, 0))
dates.Select
Selection.TextToColumns Destination:=n, DataType:=xlFixedWidth, _
FieldInfo:=Array(0, 3)
Next n
End Sub
The code currently counts the number of entries and performs text to column operation on that many dates (as to not operate all the cells which I think would slow it down?). Either way the macro currently gives me different results to the manual operation even though all the parameters of Text to Column were taken from a recording.
For some reason the entries which were originally aligned to the right have their MM and DD swapped when done manually but NOT by the macro.
Any hint on where I am going wrong would be much appreciated!
P.s. I know I should avoid selecting cells and work with ranges I will fix that bit once I know this method works.
I'm trying to establish the minimum date and its associated row for later use in a subroutine.
I'm hitting an error and i've spent the last few hours isolating the issue and searching for the solution to no avail.
I have a spreadsheet where column B contains a range of dates arranged in order. I can find the minimum date (the message box correctly returns 11/14/2015), but when I try use that date value to identify the row number I get error 91. Here is my code:
Sub testing()
ThisWorkbook.Worksheets("Burn Curve Data").Activate
Dim rDateColumn As Range
Dim dMinDate As Date
Set rDateColumn = ActiveSheet.Range("B:B")
dMinDate = Application.WorksheetFunction.Min(rDateColumn)
MsgBox dMinDate
Dim rMinCell As Range
Dim intMinRow As Integer
Set rMinCell = rDateColumn.Find(dMinDate, LookIn:=xlValues, LookAt:=xlWhole)
intMinRow = rMinCell.Row
MsgBox intMinRow
End Sub
I tried inserting an If Not statement after Set rMinCell and determined that range.find is not finding the date. Here is the statement I used to identify the error, but I deleted it to clean up the code for this posting.
If Not rMinCell is Nothing Then
intMinRow = rMinCell.Row
Else
MsgBox "error finding rMinCell"
End If
I also tried re-saving dMinDate into a string then using that string in the range.find but I encountered the same error of not finding the date.
Another nuance that may or may not be relevant is that this data exists within a named range on the worksheet. What am I doing wrong with my range.find line?!?
As discussed in the comments it appears the issue arises when the column is formatted as something other than Date.
To do this via code you can add this line after you set the rDateColumn variable:
rDateColumn.NumberFormat = "m/d/yyyy"
This should format the column as a date and your Find method should work appropriately.
Alternatively you can select the column, click 'Format Cells' and then ensure 'Date' is selected under Category.
I must be having a brain fog at this point because I am certain this is easy to do, and in fact I have managed to create other functions that are a bit more complicated for this project.
Anyway, what I am trying to do. I have a sheet (inventory-data) and in column 1, it lists a company name, which is a same for all the rows. i.e. each of the 1900 or so rows have companyname in the first cell.
Now, while the data will always be the same at each application, the number of rows will change.
So, I need a function that will first determine what the last row of data is in the range, and then change all of the cells in column one of each record to name_company. The company names will always be the same so I can staticly assign them. Here is what I have that does not work.
I was able to get it to work another way, but it would replace text all the way down to the very last row of the worksheet, way beyond where the data stops.
Thanks!
Sub changeCompany() 'Changes company name as pulled from Agemni into proper ETA format
Dim myCell As Range
Dim RngToChange As Range 'The range of cells that need to be changed
Dim LastRow As Long 'Declare variable to help determine the last row on a variable length worksheet
Dim i As Integer
With Worksheets("inventory-data") 'set the range to change
Set RngToChange = .Columns(1)
End With
LastRow = Worksheets("inventory-data").UsedRange.Rows.Count 'Have Excel determine what the last row is.
For i = LastRow To 1 Step -1
RngToChange.Cells.Value = "name_company"
Next i
End Sub
I've always had more success with [SomeCellOrRange].CurrentRegion.Rows.Count e.g:
Range("A1").CurrentRegion.Rows.Count
UsedRange looks for any use of cells, not limited to a continuous tabular block. It also sometimes needs you to re-save the workbook before it will properly shrink after you have eliminated some rows.