application.run(macro,Arg1,Arg2)

时间:2017-04-06 04:38:40

标签: excel vba excel-vba

我想请求以下问题的协助:

我正在尝试运行一个运行多个宏的宏,但它基于2个字符串,如下所示:

Sub ExportDatatoCountriesSheets()

    Dim shtnme As String
    Dim country As String

    ' United States
    shtnme = "US"
    country = "United States"
    ' ClearLatestData
    Application.Run "ClearLatestData"
    ' FilterExportDataByCountry
    Application.Run "FilterExportDataByCountry"

    ' Japan
    shtnme = "JP"
    country = "Japan"
    ' ClearLatestData
    Application.Run "ClearLatestData"
    ' FilterExportDataByCountry
    Application.Run "FilterExportDataByCountry"

End Sub

'==============================================================

Sub ClearLatestData()

    Dim shtnme As String
    Dim country As String
    Sheets(CStr(shtnme)).Activate
    Columns("A:Z").Select
    Selection.Clear

End Sub

'==============================================================

Sub FilterExportDataByCountry
Sheets("WEEKLY DATA").Select
    ActiveSheet.Range("$A$1:$G$240").AutoFilter Field:=3,    Criteria1:=CStr(country)
    Columns("A:G").Select
    Selection.Copy
    Sheets(CStr(shtnme)).Activate
    Range("A1").Select
    ActiveSheet.Paste

然而,我一直在收到错误。我基本上想要在我输入代码并通过Application.Run运行其他代码时重复设置ExportDatatoCountriesSheets

我已经搜索过,最接近的解决方案是使用参数运行宏,但是当我定义参数时,宏运行不正常并发生错误。

Application.Run (ClearLatestData, shtnme = "US", country = "United States")

请尽可能告知。

1 个答案:

答案 0 :(得分:1)

要拨打" ClearLatestData " MACRO(Sub)您需要将2个参数添加到接收Sub。所以语法应该是:

Sub ClearLatestData(shtnme As String, country As String)

Sub ClearLatestData内,您将删除声明String变量的2行:

Dim shtnme As String
Dim country As String

要使用Sub ClearLatestDatashtnme致电country,请使用:

Application.Run "ClearLatestData", shtnme, country

或者,"清洁工"更短的版本:

ClearLatestData shtnme, country

<强>代码

Sub ExportDatatoCountriesSheets()

Dim shtnme As String
Dim country As String

' United States
shtnme = "US"
country = "United States"
' ClearLatestData
ClearLatestData shtnme, country ' <-- call the MACRO    
' FilterExportDataByCountry
Application.Run "FilterExportDataByCountry"

' Japan
shtnme = "JP"
country = "Japan"

' ClearLatestData
ClearLatestData shtnme, country ' <-- call the MACRO    
' FilterExportDataByCountry
Application.Run "FilterExportDataByCountry"

End Sub

' ================================================================

Sub ClearLatestData(shtnme As String, country As String)

    Sheets(CStr(shtnme)).Activate
    Columns("A:Z").Select
    Selection.Clear

End Sub

注意:建议您远离ActivateSelectSelection,并使用合格的Worksheets,{ {1}}和其他对象。

例如,而不是下面的3行:

Range

您可以使用一行(由于您不使用Sheets(CStr(shtnme)).Activate Columns("A:Z").Select Selection.Clear Activate,因此速度会更快):

select