首页 > 解决方案 > 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

标签: excelvba

解决方案


推荐阅读