用户输入或事件过程与被叫过程(VBA)

时间:2016-04-14 12:18:54

标签: vba excel-vba excel

有没有办法判断某个程序是从事件或用户输入运行还是从另一个宏调用的程序?

例如,如果从另一个宏调用过程,则表示Boolean值吗?

显然,下面的代码没有实际意义,但你明白了。

dim macro

     macro = called.proccedure
   if macro = true then
      'do what ever
   end if

2 个答案:

答案 0 :(得分:0)

您可以使用Application.Caller收集有关调用程序的位置的信息。

我使用Application.Caller.Column来查找我的数据来自哪个位置以满足条件。

我如何使用该方法的示例:

 If Application.Caller.Column = 20 Then Call ChangeDirectionForSellSide(firstLegBuySell, secondLegBuySell, futureLegBuySell)

    'First option leg built
    chatConfirmString = "You " & firstLegBuySell & " " & Format(firstLegQuantity, "#,##0") & DetermineProductMeasurementType(productType, tradeDataRange.Item(2).Value, contractMonth) & " " & productType & " " & tradeDataRange.Item(2).Value & " " & contractMonth & " " & Format(tradeDataRange.Item(6).Value, "#,###.00##") & " " & tradeDataRange.Item(7).Value & " @ "

    'Formats the price type
    If productType = "WTI" Or productType = "BRT ICE" Or productType = "FO 3.5%" Or productType = "GO" Then

        chatConfirmString = chatConfirmString & Format(tradeDataRange.Item(8).Value, "#,###.00")

    Else

        chatConfirmString = chatConfirmString & Format(tradeDataRange.Item(8).Value, "#,###.0000")

    End If

您在上面发布的代码存在一些问题。 您正在使用应用程序语法错误(来自误解)。您必须将其称为Application.Caller.“您想要引用的任何对象”。程序不是对象(至少据我所知,它们不是),但是代码中可能出现的可能情况是什么?这是否适用于UDF,因此可以返回范围?可以退回一张纸吗?程序在哪里?这些是我们需要回答的问题,以便准确地创建一个将布尔值计算为true或false的条件。

答案 1 :(得分:0)

如果我的理解是正确的,那么只有将子/过程/事件名称硬编码到某个变量中的简单解决方案才能被查询以供决策

我记得我在SO中读到了一个很好的深入线索,最后,在深入研究非常复杂的解决方案之后,最简单的解决方案是我上面写的

并且几乎必须使用Public变量,以使其尽可能简洁:

例如:

Option Explicit

Public thingName As String


Sub main()

thingName = "Main" '"Mark" you're in 'Main' sub

'...
Call DoSomething 'call DoSomething() procedure

End Sub


Sub DoSomething()

thingName = "DoSomething" '"Mark" you're in 'DoSomething' sub

MsgBox ReturnSomething ' ReturnSomething() function

'...

End Sub


Function ReturnSomething()

thingName = "ReturnSomething" '"Mark" you're in 'ReturnSomething' Function

'...
ReturnSomething = "something"

End Function

当然应该扩展到任何Userform事件处理程序subs

更精确且(希望)有用但冗长的版本是:

Option Explicit

Public Type Thing
    Name As String
    Type As String
    Job As String
End Type
Dim myThing As Thing


Sub main()

'"Mark" you're in 'Main' sub
With myThing
    .Name = "Main"
    .Type = "Sub"
    .Job = "main procedure"
End With

'...
Call DoSomething 'call DoSomething() procedure    

End Sub


Sub DoSomething()

'"Mark" you're in 'DoSomething' sub
With myThing
    .Name = "DoSomething"
    .Type = "Sub"
    .Job = "procedure to do something"
End With


MsgBox ReturnSomething 'call ReturnSomething() function

'...

End Sub


Function ReturnSomething()

'"Mark" you're in 'ReturnSomething' Function
With myThing
    .Name = "ReturnSomething"
    .Type = "Function"
    .Job = "procedure to return something"
End With

'...
ReturnSomething = "something"

End Function