application.run(macros,Arg1,Arg2)

我想请以下问题提供协助:

我试图运行一个macros来运行多个macros,但它是基于2个string,如下所示:

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 

但是,我不断收到错误。 我基本上想要设置ExportDatatoCountriesSheetsmacros来重复,而我input的代码,并通过Application.Run运行其他人

我search和最接近的解决scheme是运行macros的参数,但是当我定义的参数macros不能正常运行,发生错误。

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

如果可能,请告知。

为了调用“ ClearLatestData ”MACRO( Sub ),您需要将2个参数添加到接收Sub 。 所以语法应该是:

 Sub ClearLatestData(shtnme As String, country As String) 

Sub ClearLatestData里面,你将删除两行声明Stringvariables:

 Dim shtnme As String Dim country As String 

要使用shtnmecountry调用Sub ClearLatestData ,请使用:

 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 

注意 :build议远离ActivateSelectSelection ,并使用合格的WorksheetsRange和其他对象。

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

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

您可以使用单行(因为您不使用Activateselect ,所以速度会更快):

 Sheets(shtnme).Columns("A:Z").Clear