将子函数名称作为函数中的参数传递

时间:2016-05-05 17:00:44

标签: excel vba excel-vba

我有一个userform,它在工作簿中有一个工作表名称列表框,有三个按钮:一个删除列表框中选中的所有工作表,一个只清除那些工作表,另一个删除该工作表中的图表。我目前有三个看起来几乎相同的子函数,因为每个函数只根据所选按钮在循环上运行一个子函数:

<display-name>Assignment5</display-name>

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

为了解决这个问题,我决定开发一个这样的子功能:

Sub DeleteSheets() 'Removes sheets selected by user in ListBox

    For k = 0 To sheetNameListBox.ListCount - 1      
     If sheetNameListBox.Selected(k) = True Then     
      DeleteSheet sheetNameListBox.List(k)           
     End If
    Next k

End Sub

Sub ClearSheets() 'Clears sheets selected by user in ListBox

    For k = 0 To sheetNameListBox.ListCount - 1       
     If sheetNameListBox.Selected(k) = True Then      
      ClearSheet sheetNameListBox.List(k)              
     End If
    Next k

End Sub

Sub DeleteCharts() 'Removes charts from sheets selected by user

    For k = 0 To sheetNameListBox.ListCount - 1   
     If sheetNameListBox.Selected(k) = True Then  
      DeleteChart sheetNameListBox.List(k)        
     End If
    Next k

End Sub

这似乎也是低效的,因为我必须为每个案件分三个案例。有没有办法可以直接输入我想要调用的函数的名称,让它运行?

1 个答案:

答案 0 :(得分:3)

以下是here

公然被盗的答案
Sub test() 
    Dim ftnName As String 
    Dim argument As String 
    Dim result As String 

    ftnName = "myFunction" 
    argument = "cat" 

    result = Application.Run(ftnName, argument) 

    MsgBox result 
End Sub 

Function myFunction(inString As String) As String 
    myFunction = inString & " has " & Len(inString) & " letters." 
End Function