问题
This is about my Result/Target workbook, I have 2 sheets "Open" and "sheet2", these codes apply vlookup formula from row 2 to end of range in last available empty column of the sheet "Open". The entire first row in the sheet "Open has dates, is it possible to apply formula to the column of respective date which matches date in Sheet2 cell "A1" instead of last empty column??
Sub GET_BHAV()
Dim VlookUpVal As Variant
Dim OpenWs As Worksheet, HighWs As Worksheet, bhavWs As Worksheet
Dim OpenLastRow As Long, bhavLastRow As Long, x As Long
Dim bhavRng As Range
Set OpenWs = ThisWorkbook.Worksheets("Open")
Set HighWs = ThisWorkbook.Worksheets("High")
Workbooks.Open "C:\Users\playt\Desktop\STACK\VANGU\cm07JAN2020bhav.csv"
Set bhavWs = Workbooks("cm07JAN2020bhav.csv").Worksheets("cm07JAN2020bhav")
bhavLastRow = bhavWs.Range("A" & Rows.Count).End(xlUp).Row
OpenLastRow = OpenWs.Range("A" & Rows.Count).End(xlUp).Row
HighLastRow = HighWs.Range("A" & Rows.Count).End(xlUp).Row
Set bhavRng = bhavWs.Range("A2:G" & bhavLastRow)
With OpenWs
For x = 2 To OpenLastRow
'On Error Resume Next
VlookUpVal = Application.VLookup(.Range("A" & x).Value, bhavRng, 3, False)
'gives #NA value to cell with error
If IsError(VlookUpVal) Then
.Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = "#NA"
' highlights cell color on error
.Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 0).Interior.ColorIndex = 3
Else
.Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = VlookUpVal
End If
Next x
With HighWs
For x = 2 To HighLastRow
VlookUpVal = Application.VLookup(.Range("A" & x).Value, bhavRng, 4, False)
If IsError(VlookUpVal) Then
.Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = "#NA"
Else
.Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = VlookUpVal
End If
Next x
End With
End With
End Sub
来源:https://stackoverflow.com/questions/60080041/define-vlookup-result-column-by-changing-date-in-specified-cell