我有一个包含Excel工作表数据的表格; 这是图像IMAGE
的链接我在VBA中写了一个函数函数 myFunction(isin as variant,dt as date),它应该找到与isin对应的值和给定日期的最近日期dt(不在日期dt之后)。
以下是我的代码示例。
Function myFunction(isin As Variant, dt As Date)
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("sheet1")
Dim last_row As Integer
last_row1 = ws.Range("A1").End(xlDown).Row
myFunction = WorksheetFunction.VLookup(isin, ws.Range("A1:C" & last_row1), 3, False)
End Function
这使用了Excel的vlookup功能,但我无法想象如何找到目标值。
答案 0 :(得分:0)
我仍然需要测试此代码,但概念是您定义所有信息的位置。然后浏览每一行,找出哪些名称匹配。当你找到一个匹配数字时,如果日期更近或没有。如果它更新,您的比较和存储在列表中的位置。当您浏览完列表后,返回您存储的第三列的值。
现在在提供不在列表中的名称的情况下,我已设置此函数以返回值0。
Option Explicit
Function myFunction(isin As String, dt As Date) As Double
Dim ws As Worksheet
Dim last_row As Integer
Dim Header_row As Integer
Dim Name_Col As Integer
Dim Date_Col As Integer
Dim Value_Col As Integer
Dim counter_X As Integer
Dim Temp_Index As Integer
Dim Temp_Date As Date
Set ws = Worksheets("Sheet1")
'define the your table information
Header_row = 1
last_row = ws.Range("A1").End(xlDown).Row
Name_Col = 1
Date_Col = 2
Value_Col = 3
'Initialize variables
Temp_Date = 0
With ws
For counter_X = Header_row + 1 To last_row
If .Cells(counter_X, Name_Col).Value = isin Then
If .Cells(counter_X, Date_Col).Value <= dt Then
If .Cells(counter_X, Date_Col).Value > Temp_Date Then
Temp_Date = .Cells(counter_X, Date_Col).Value
Temp_Index = counter_X
End If
End If
End If
Next counter_X
If Temp_Date = 0 Then
myFunction = 0
Else
myFunction = .Cells(Temp_Index, Value_Col).Value
End If
End With
End Function