在多个Excel工作表上运行macros

我正在寻求帮助,在多个Excel工作表上运行一个macros(以前有几个相关的问题,但我不认为/知道他们是否适用于我的问题)。 每张表有不同的自动收报机。 我正在尝试在每个Excel工作表上拉出不同股票的历史股价。 您将从VBA代码中注意到,每个工作表的代码都位于K1中。

现在,我可以使用下面的代码在多个工作表上运行相同的macros。 但是,macros运行使用相同的所有工作表的股票。 例如,第一个工作表中的股票代码是“WMT”,macros将使用“WMT”在所有工作表上拖动历史股票价格,而不是每个工作表的唯一代码。 有谁知道如何使macros在每个工作表上运行,以便macros使用位于每个工作表上的唯一股票?

Sub Data_Get() ' ' Data_Get Macro ' Dim ticker As String, sday, smonth, syear, eday, emonth, eyear As Long, ws As Worksheet ticker = Range("k1") sday = Day(Range("k2")) smonth = Month(Range("k2")) - 1 syear = Year(Range("k2")) eday = Day(Range("k3")) emonth = Month(Range("k3")) - 1 eyear = Year(Range("k3")) ' For Each ws In Sheets ws.Activate Columns("A:G").ClearContents With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;http://real-chart.finance.yahoo.com/table.csv?s=" & ticker & "&d=" & emonth & "&e=" & eday & "&f=" & eyear & " &g=w&a=" & smonth & "&b=" & sday & "&c=" & syear & "&ignore=.csv" _ , Destination:=Range("$A$1")) .Name = "Datatable" .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .TextFilePromptOnRefresh = False .TextFilePlatform = 437 .TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = True .TextFileTabDelimiter = False .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(5, 1, 1, 1, 1, 1, 1) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With Next ws End Sub 

这里是如何循环工作簿中的所有工作表,并调用你的子。

  Dim iIndex as integer Dim ws As Excel.Worksheet For iIndex = 1 To ActiveWorkbook.Worksheets.count Set ws = Worksheets(iIndex) ws.Activate Data_Get Next iIndex 

你有任务

ticker = Range("k1")

你进入你的主循环之前。 如果K1在每个工作表上有一个不同的值,并且您希望代码引用这个值 – 您需要将该行移到主循环中(比如ws.Activate之后)。 对于引用特定单元格的其他作业也有类似的说法。 如果你在循环之前运行赋值,那么循环将不会改变它们的值。

通常,您需要在所有表单上运行macros,而不是一个。 例如,您将所有工作表中的数据收集到工作表“报告”中:

 Dim Sh As Excel.Worksheet For Each Sh in ActiveWorkbook.Worksheets If Sh.Name <> "Report" Then Data_Get Sh Next Sh 

这将需要更改您的原始macros并使其独立于活动工作表:

 Sub Data_Get(Sh As Worksheet) [...] ticker = Sh.Range("k1") sday = Day(Sh.Range("k2"))