我正在尝试创建编号变量(即,suminterest_X,其中“X”从1到20,并产生20个不同的变量,一个用于循环中的每个进程)。
我的代码目前是:
让DateTime
但是,在编写此行时,我会收到语法错误。
编写行时语法有效:
suminterest_& CStr(i) = Excel.WorksheetFunction.Sum(Range(Worksheets("Bond_" & CStr(i)).Cells(8, 5), Worksheets("Bond_" & CStr(i)).Cells(7 + wam1, 5)))
在早期的代码中使用。
任何人都可以帮我解释如何正确编码吗?
编辑:
这是我的整个循环:
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 3) = j
create the variables and tables
For i = 1 To 20
'assingment of variables
Let wac1 = Cells(3 + i, 2)
Let wam1 = Cells(3 + i, 3)
Let prince1 = Cells(3 + i, 4)
Let annualdef1 = Cells(3 + i, 5)
Let annualprepay1 = Cells(3 + i, 6)
Let loss1 = Cells(3 + i, 7)
'creation of tables
For j = 1 To wam1
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 3) = j
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 4) = prince1
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 5) = ipayment(prince1, wac1)
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 7) = preprince(prince1, annualprepay1, j, wam1)
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 8) = defprince(prince1, annualdef1)
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 6) = schedpay(prince1, Worksheets("Bond_" & CStr(i)).Cells(7 + j, 8), j, wam1)
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 9) = recovprince(Worksheets("Bond_" & CStr(i)).Cells(7 + j, 8), loss1)
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 10) = totprincepaid(Worksheets("Bond_" & CStr(i)).Cells(7 + j, 6), Worksheets("Bond_" & CStr(i)).Cells(7 + j, 7), Worksheets("Bond_" & CStr(i)).Cells(7 + j, 8), recov1(loss1))
Worksheets("Bond_" & CStr(i)).Cells(7 + j, 11) = balance1(Worksheets("Bond_" & CStr(i)).Cells(7 + j, 4), Worksheets("Bond_" & CStr(i)).Cells(7 + j, 6), Worksheets("Bond_" & CStr(i)).Cells(7 + j, 7), Worksheets("Bond_" & CStr(i)).Cells(7 + j, 8))
prince1 = Worksheets("Bond_" & CStr(i)).Cells(7 + j, 11)
Next j
suminterest = Excel.WorksheetFunction.Sum(Range(Worksheets("Bond_" & CStr(i)).Cells(8, 5), Worksheets("Bond_" & CStr(i)).Cells(7 + wam1, 5)))
我希望能够将20个suminterest中的每一个存储为自己的变量,并输入范围(“M1”)= suminterest_X来获取相应的变量。
答案 0 :(得分:0)
在Worksheets("Bond_" & CStr(i)).Cells(7 + j, 3) = j
中,您将字符串分配给"Bond_"
,而不是变量。
如果你想在数组中有一些String
值,通过循环分配,就像这样:
然后您可以通过以下代码完成此操作:
Sub TestMe()
Dim myArr As Variant
Dim cnt As Long
ReDim myArr(5)
For cnt = 0 To 5
myArr(cnt) = "suminterest_" & cnt
Next
End Sub
答案 1 :(得分:0)
您希望将数字存储在数组中( of variables )
使用数组,您可以返回suminterest(i)
而不是suminterest_& CStr(i)
Public Sub Test()
Dim SumInterest(1 To 20) As Double
Dim i As Long
For i = 1 To 20
SumInterest(i) = i * 2
Next i
Dim ReturnFrom As Long
ReturnFrom = InputBox("Enter number between 1 and 20.")
MsgBox "The value at position " & ReturnFrom & " is: " & SumInterest(ReturnFrom)
End Sub
Dim SumInterest(20)
将
给你21个值(0 - 20)。Dim SumInterest(1 To 20)
REDIM
调整数组大小。LBOUND(SumInterest)
找到数组的下限(在我的示例中返回1)。 UBOUND(SumInterest)