excel - VBA 错误“1004”:对象“_Global”的方法“范围”失败
问题描述
我正在关注一本关于模拟布朗运动的书,并且出现了这个错误,感谢任何帮助。
调试标志:
Worksheets("scratch").Range(Range("start"), Range("start").End(xlDown)).Clear
主要代码如下:
Option Explicit
Sub RandomWalk()
Dim walk() As Double
Dim stepSize As Double
Dim steps, i As Long
steps = Range("nsteps").Value
stepSize = 1 / steps
ReDim walk(1 To steps)
walk(1) = BinaryStepSelection() * stepSize
For i = 2 To UBound(walk)
walk(i) = walk(i - 1) + BinaryStepSelection() * stepSize
Next i
Call CopySimResultsToScratch(walk)
Call PlotRandomWalk(steps)
End Sub
Function BinaryStepSelection() As Double
If (Rnd() < 0.5) Then
BinaryStepSelection = 1
Else
BinaryStepSelection = -1
End If
End Function
Private Sub CopySimResultsToScratch(walk() As Double)
Dim scratch As Range
Dim length As Long
Dim lI As Long
Application.ScreenUpdating = False
length = UBound(walk) - LBound(walk) + 1
Worksheets("scratch").Range(Range("start"), Range("start").End(xlDown)).Clear
Set scratch = Worksheets("scratch").Range(Range("start"), Range("start").Offset(length - 1))
scratch = Application.WorksheetFunction.Transpose(walk)
Application.ScreenUpdating = True
End Sub
Private Sub PlotRandomWalk(ByVal length As Long)
Dim scratch As Range
Application.ScreenUpdating = False
Set scratch = Worksheets("scratch").Range(Range("start"), Range("start").Offset(length - 1))
ActiveSheet.ChartObjects.Delete
Charts.Add
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=scratch, PlotBy _
:=xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:="BrownianMotion"
With ActiveChart
.HasTitle = True
.ChartTitle.Characters.Text = "Random Walk"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "t"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "W"
With .Parent
.Top = Range("B12").Top
.Left = Range("B12").Left
End With
End With
Application.ScreenUpdating = True
End Sub
解决方案
推荐阅读
- python - 为什么我们仍然可以在 Python 中读取字节值
- python - 如何使用Groupby计算熊猫中两列中遵循条件的行数
- node.js - 从 gitlab 管道将 node.js 应用程序部署到 AWS EB 时出现问题
- node.js - 在 Jwt 和护照中使用“用户名”字段
- react-native - 如何使日期选择器默认为空
- c++ - 将项目从 VS2010 升级到 2015 时如何修复 chrono 上的编译错误
- angular - ngx-translate 在模块的所有子组件中进行翻译
- ios - 如何选择模拟器版本
- reactjs - 创建反应应用程序苹果触摸图标不起作用
- python - 如何将此单线转换为返回 k 个元素的生成器?