【发布时间】:2019-06-25 13:42:44
【问题描述】:
我目前正在处理 VBA 代码,您可以在输入框中输入日期,格式如下:YYYY-MM。
然后我使用一个函数来查找其值与输入框的值匹配的单元格,并在具有所述日期的单元格下方的行中复制信息。 每 7 列用于一个日期的数据(第 1 列是风险价值,第 2 行是风险价值的变化,第 3 列是市场价值,第 4 列是市场价值的变化等)和每一行代表不同的投资组合。每个投资组合的数据都是从其他工作簿复制而来的。
接下来的 7 列是上个月的数据。
我现在想计算一个月到另一个月的风险价值变化。
为此,我需要找到在输入框中输入的日期之前的月份日期,并从该列复制有风险的值,将其分配给变量,最后通过公式:(当前风险值 - 之前的风险值)/(之前的风险值)。市场价值的变化也是如此。
我不知道该怎么做,因为我对 VBA 很陌生。任何帮助将非常感激。这是我到目前为止所拥有的:
Option Explicit
Function MatchHeader(strSearch As String) As Long
Dim myRight As Long, Colcount As Long
myRight = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
For Colcount = 1 To myRight
If ActiveSheet.Cells(1, Colcount) = strSearch Then
MatchHeader = Colcount
Exit For
End If
Next Colcount
End Function
Sub StressTest()
Dim index As Integer
Dim dateColumn As Integer
Dim portfolioName As Variant
Dim portfolioDate As String
Dim ParametricVar As Double
Dim AuM As Double
Dim strPath As String
Dim strFilePath As String
Dim wb As Workbook
Dim sheet As Worksheet
Set wb = ThisWorkbook
Set sheet = ActiveSheet
portfolioDate = InputBox("Please enter date under the following form : YYYY-MM", "Date at the time of Stress Test", "Type Here")
Debug.Print "InputBox provided value is: " & portfolioDate
For index = 3 To Cells(Rows.Count, "A").End(xlUp).Row
dateColumn = MatchHeader(portfolioDate)
portfolioName = ActiveSheet.Range("A" & index & "").Value
strPath = "G:\Risk\Risk Reports\VaR-Stress test\" & portfolioDate & "\" & portfolioName & ""
Set wb = Workbooks.Open(strPath)
ParametricVar = Workbooks(portfolioName).Worksheets("VaR Comparison").Range("B19")
AuM = Workbooks(portfolioName).Worksheets("Holdings - Main View").Range("E11")
sheet.Cells(index, dateColumn).Value = ParametricVar / AuM
sheet.Cells(index, dateColumn + 2).Value = AuM
sheet.Cells(index, dateColumn + 5).Value = Application.WorksheetFunction.Min(Workbooks(wb).Worksheets("VaR Comparison").Range("P11:AA11"))
sheet.Cells(index, dateColumn + 6).Value = Application.WorksheetFunction.Max(Workbooks(wb).Worksheets("VaR Comparison").Range("J16:J1000"))
wb.Close Savechanges:=False
Next index
End Sub
【问题讨论】:
-
我应该将portfolioDate设置为日期而不是字符串吗?
-
我将添加一个答案以对此进行扩展