我想定义一个空数组,以便可以在代码中进一步为其定义值,但是我不断在此行上获取“下标超出范围”,运行时错误为“ 9”:
ReDim VectorToSum(0 To q-1)
不确定为什么。 这是完整的代码:
Option Explicit
Public Sub DefferedRev()
Dim NoMonths As Range
Set NoMonths = ThisWorkbook.Worksheets("Sheet4").Range("C13")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet13")
If ws.Range("B40").Value = ws.Range("C82").Value Then
ws.Range(ws.Cells(48, 5), ws.Cells(48, 7)).Value = 0
Else
Dim i As Long
For i = 5 To 7
Dim q As Long
q = (i Mod NoMonths) - 5
Dim VectorToSum() As String
ReDim VectorToSum(0 To q-1)
Dim w As Long
For w = 0 To q-1
VectorToSum(w) = (ws.Cells(38, i).Value * ws.Cells(7, i).Value) / (NoMonths * NoMonths - w)
Next w
ws.Cells(48, i).Value = Application.WorksheetFunction.Sum(VectorToSum)
Next i
End If
End Sub
我尝试过:
q = (i Mod NoMonths) - 5
Dim VectorToSum() As Long
Dim w As Long
For w = 0 To q
ReDim VectorToSum(w)
VectorToSum(w) = (ws.Cells(38, i).Value * ws.Cells(7, i).Value) / (NoMonths * NoMonths - w)
Next w
ws.Cells(48, i).Value = Application.WorksheetFunction.Sum(VectorToSum)
Next i
但是我在以下行中得到一个运行时错误5:
ws.Cells(48, i).Value = Application.WorksheetFunction.Sum(VectorToSum)
答案 0 :(得分:-1)
@JohnColeman
完成您的建议,现在我在此行上收到运行时错误6:
Sum = Sum + (ws.Cells(38, i).Value * ws.Cells(7, i).Value) / (NoMonths * NoMonths - w)
您认为现在可能是什么问题? 完整代码:
Option Explicit
Public Sub DefferedRev()
Dim NoMonths As Range
Set NoMonths = ThisWorkbook.Worksheets("Licence Central").Range("C13")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("73 Licence C")
If ws.Range("B40").Value = ws.Range("C82").Value Then
ws.Range(ws.Cells(48, 5), ws.Cells(48, 7)).Value = 0
Else
Dim i As Long
For i = 5 To 7
Dim q As Integer
q = (i - 5 Mod NoMonths)
' Dim VectorToSum() As String
'ReDim VectorToSum(0)
Dim w As Long
Dim Sum As Long
Sum = 0
For w = 0 To q
Sum = Sum + (ws.Cells(38, i).Value * ws.Cells(7, i).Value) / (NoMonths * NoMonths - w)
Next w
ws.Cells(48, i).Value = Sum
Next i
End If
End Sub
答案 1 :(得分:-2)
您的数组是一个维度,因此您可以通过切换到脚本来删除与Redim有关的问题。字典(或ArrayList)
对于Scripting.Dictionary,您需要添加对Microsoft Scritpting运行时的引用
对于数组列表,您将需要添加对mscorlib的引用,您需要将其浏览至C:\ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ mscorlib.dll(如果使用的是64,则为Frameword64位办公室)
Public Sub DefferedRev()
Dim NoMonths As Range
Set NoMonths = ThisWorkbook.Worksheets("Sheet4").Range("C13")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet13")
If ws.Range("B40").Value = ws.Range("C82").Value Then
ws.Range(ws.Cells(48, 5), ws.Cells(48, 7)).Value = 0
Else
Dim i As Long
For i = 5 To 7
Dim q As Long
q = (i Mod NoMonths) - 5
Dim VectorToSum As Scripting.Dictionary
Dim w As Long
Set VectorToSum = New Scripting.Dictionary
For w = 0 To q - 1
VectorToSum.Add w, (ws.Cells(38, i).Value * ws.Cells(7, i).Value) / (NoMonths * NoMonths - w)
Next w
ws.Cells(48, i).Value = Excel.Application.WorksheetFunction.Sum(VectorToSum.Items)
Next i
End If
End Sub