问题
I am looking to find a variable within a row and return the column reference. The code I have written so far is;
Dim VarianceDate As String
VarianceDate = Sheets("Summary").Range("C12").Value
Rows("6").Find(What:=VarianceDate, After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
TargetCol = ActiveCell.Column
In this example the Variance date is 01/06/2015, however when I stepinto the code in VBA it returns nothing. Except When I search for it manually It finds the correct cell.
Eventually I would like to use the TargetCol reference to help me extract the correct data into another workbook.
Any help would be much appreicated.
Thanks
回答1:
You need to mention that the search term is a date and also if the activecell is not in your find range, it will throw an error due to the inclusion of After:=ActiveCell
Try the following code
Sub FindDateCol()
Dim VarianceDate As String: VarianceDate = Sheets("Summary").Range("C12").Value
Dim TargetCell As Range, TargetCol As Integer
Set TargetCell = Rows("6").Find(What:=CDate(VarianceDate), LookIn:=xlFormulas, LookAt:=xlPart)
If Not TargetCell Is Nothing Then TargetCol = TargetCell.Column
MsgBox TargetCol
End Sub
来源:https://stackoverflow.com/questions/31186598/find-date-variable-within-a-row-and-return-column-vba