从其他工作簿中使用application.run时,目标搜索运行时1004错误

时间:2019-01-12 18:27:43

标签: excel vba

尽管在许多论坛中进行了深入搜索,但我仍然遇到无法解决的运行时错误。

这是问题所在:我正在模型中使用宏,以通过目标搜索功能寻找最佳分配。 当我在该模型中使用它(称为模型1)时,宏可以完美运行。

但是,我需要在该模型中工作,并在另一个模型中工作,以获取将填充第3个excel文件中的表的数据,该文件即为我的“主文件”(我们将其称为Model 3)。

因此,我需要通过Model 3中的Application.run调用位于Model 1中的宏。 并且这样做时,我收到“运行时错误'1004':引用无效”。这与我在模型1中使用的“目标搜索”功能有关。 此外,如果之后我回到模型1并尝试使用该宏,则在使用宏之前,我会得到完全相同的错误消息。

这是我的代码: 模型3(主):

Sub Test_Optim()
Dim JFMPath As String
Dim MacroPath As String

JFMPath = Sheets("Inputs").Range("D2")
MacroPath = Sheets("Inputs").Range("A3")

Workbooks.Open JFMPath
Application.Run (MacroPath)

End Sub

模型1:

Option Explicit
Option Base 1
Sub Optimization_Alloc()
'Definitions

Dim i As Integer
Dim k As Integer
Dim IRR As Single
Dim IRRDelta As Single
Dim vIRR() As Single
Dim MinIRR As Single

Dim vPPA() As Single
Dim PPALevel As Single
Dim MinPPA As Single

Dim Position As Integer
Dim FlipYearIterations As Integer

Dim IterTF As Boolean
Dim IterStep As Single

Dim FlipYear As Integer
Dim OptFlipYear As Integer
Dim vFlipYear() As Integer

Dim xDistribution As Single
Dim OptxDistribution As Single
Dim vXDistribution() As Single

'enables goal-seek iterations, MaxIterations is the number you would wanna change
IterTF = Application.Iteration = True
IterStep = Application.MaxIterations

With Application
 .Iteration = True
 .MaxIterations = 500
 .MaxChange = 0.0001
End With


FlipYearIterations = 10

ReDim vPPA(FlipYearIterations) As Single
ReDim vFlipYear(FlipYearIterations) As Integer
ReDim vXDistribution(FlipYearIterations) As Single
ReDim vIRR(FlipYearIterations) As Single

For i = 1 To FlipYearIterations
    vFlipYear(i) = 2027 + i - 1
Next i

'Loops through different FlipYears. For every year, optimal allocation of cash/tax is calculated by goalseek.
For k = 1 To FlipYearIterations
    Worksheets("As_Yr").Cells(345, 9) = vFlipYear(k) 'Optimal flip year
    Worksheets("As_Yr").Cells(350, 9).GoalSeek Goal:=0, ChangingCell:=Worksheets("As_Yr").Cells(346, 9)
    'Here is the Goalseek function from which I get the run-time error

    xDistribution = Worksheets("As_Yr").Cells(346, 9)
    PPALevel = Worksheets("Cockpit & As_Gen").Cells(48, 9)

    vXDistribution(k) = xDistribution
    vPPA(k) = PPALevel
    vIRR(k) = Worksheets("As_Yr").Cells(348, 9) 
Next k

'Determines optimal FlipYear
MinIRR = WorksheetFunction.Max(vIRR)
Position = WorksheetFunction.Match(MinIRR, vIRR, False)

OptFlipYear = vFlipYear(Position)
OptxDistribution = vXDistribution(Position)


'Prints optimal setting to Excel
Worksheets("As_Yr").Cells(345, 9) = OptFlipYear 'Optimal flip year
Worksheets("As_Yr").Cells(346, 9) = OptxDistribution 'Optimal CF distrib


'restores to the original goal-seek iterations setting
IterTF = Application.Iteration = True
IterStep = Application.MaxIterations

With Application
 .MaxIterations = IterStep
 .Iteration = IterTF
 .MaxChange = 0.001
End With

End Sub

这是你们其中一个可以帮助我的事情吗? 我想这是一个虚假的错误,但我无法弄清楚。

非常感谢, 爱丽丝

0 个答案:

没有答案