我一直给变量赋值,但它保持为空

时间:2019-06-24 13:03:04

标签: excel vba

我目前正在处理一个代码,该代码应该为某个变量分配一个值,并使用分配给该变量的名称打开一个文件。 但是,每次调试代码时,VBA都会警告我,即使文件已成功打开,也不会为变量分配任何值。 这是我到目前为止的内容:

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


portfolioDate = InputBox("Please enter date under the following form : YYYY-MM", "Date at the time of Stress Test", "Type Here")


For index = 3 To 32

portfolioName = ActiveSheet.Range("A" & index & "").Value

'Error happens on this line vvv
Workbooks.Open "G:\Risk\Risk Reports\VaR-Stress test\" & portfolioDate & "\" & portfolioName & ""

ParametricVar = Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("B19")

AuM = Workbooks("" & portfolioName & "").Worksheets("Holdings - Main View").Range("E11")




Sheet1.Cells(index, dateColumn).Value = ParametricVar / AuM
Sheet1.Cells(index, dateColumn + 2).Value = ParametricVar / AuM

Sheet1.Cells(index, dateColumn + 5).Value = Application.Min(Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("P11:AA11"))
Sheet1.Cells(index, dateColumn + 6).Value = Application.Max(Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("J16:J1000"))


Next index




End Sub



2 个答案:

答案 0 :(得分:0)

您必须打开Option Explicit设置,如here所述。

在这种情况下,您会注意到,尽管声明了变量Sheet1,但并未声明。您需要:

  • 声明此变量
  • 或使用ActiveSheetWorksheets("Sheet1")代替Sheet1
  • 或使用您的语言的Sheet1代号引用,例如对于俄语:

enter image description here

使用突出显示的Лист1代替Sheet1

答案 1 :(得分:0)

将您的代码转换为此,并研究即时窗口(VBA编辑器中的Ctrl + G)以查看生成的文件路径是否正确。

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


portfolioDate = InputBox("Please enter date under the following form : YYYY-MM", "Date at the time of Stress Test")
Debug.Print "InputBox provided value is: " & portfolioDate 


For index = 3 To 32

portfolioName = ActiveSheet.Range("A" & index & "").Value
Debug.Print "ActiveSheet Name is: " & ActiveSheet.Name
Debug.Print "portfolioName value is: " & portfolioName 
Dim strFilePath As String
strPath =  "G:\Risk\Risk Reports\VaR-Stress test\" & portfolioDate & "\" & portfolioName & ""
Debug.Print strPath
Workbooks.Open strPath

ParametricVar = Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("B19")

AuM = Workbooks("" & portfolioName & "").Worksheets("Holdings - Main View").Range("E11")




Sheet1.Cells(index, dateColumn).Value = ParametricVar / AuM
Sheet1.Cells(index, dateColumn + 2).Value = ParametricVar / AuM

Sheet1.Cells(index, dateColumn + 5).Value = Application.Min(Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("P11:AA11"))
Sheet1.Cells(index, dateColumn + 6).Value = Application.Max(Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("J16:J1000"))


Next index
相关问题