如何在工作簿中的某些而不是所有工作表上运行macros?

我有一个工作簿,其中包含标准普尔500中每个行业组的工作表,并在第一张工作表上按下命令button时,写下了下面的macros来更新所有股票信息。 macros完美的工作,但是当我去添加额外的表,我不想用这个macros更新它停止工作。 我尝试使用下面的“如果不是”的声明,但似乎没有工作。

Sub Get_Stock_Quotes_from_Yahoo_Finance_API() 'Run the API for every sheet in the workbook Dim Sht As Worksheet For Each Sht In ThisWorkbook.Worksheets 'Look to see what the sheet is named and run the macro if it is not what is below If Not Sht.Name = "Cover" _ And Not Sht.Name = "Select Industry" Then Sht.Activate ' Dim varibales and set range Dim head As Range Set head = Worksheet.Range("A2") 'dim variables Dim I As Integer Dim Symbols As String: Symbols = "" Dim SpecialTags As String: SpecialTags = "" Dim Yahoo_Finance_URL As String: Yahoo_Finance_URL = "http://finance.yahoo.com/d/quotes.csv?s=" Dim rng As Range Dim cell As Range ' Get the Stock Symbols Set rng = Range(head.Offset(1, 0), head.Offset(1, 0).End(xlDown)) For Each cell In rng ' Starting from a cell below the head cell till the last filled cell Symbols = Symbols & cell.Value & "+" Next cell Symbols = Left(Symbols, Len(Symbols) - 1) ' Remove the last '+' ' Get the Special Tags Set rng = Range(head.Offset(0, 1), head.Offset(0, 1).End(xlToRight)) For Each cell In rng ' Starting from a cell to the right of the head cell till the last filled cell SpecialTags = SpecialTags & cell.Value Next ' Put the desciption/name of each tag in the cell above it Dim SpecialTagsArr() As String: Dim TagNamesArr() As String Call Get_Special_Tags(SpecialTagsArr, TagNamesArr) For Each cell In rng cell.Offset(-1, 0).Value = FindTagName(cell.Value, SpecialTagsArr, TagNamesArr) Next Yahoo_Finance_URL = Yahoo_Finance_URL & Symbols & "&f=" & SpecialTags Call Print_CSV(Yahoo_Finance_URL, head) Next Sht 'At the end of the program say it has all been updated MsgBox ("All Data Updated") End Sub 

更改

  If Not Sht.Name = "Cover" _ And Not Sht.Name = "Select Industry" Then 

 If Sht.Name <> "Cover" And Sht.Name <> "Select Industry" Then 

不要忘记你的End IfNext Sht

参考凯文的第二个代码 – 现在排除逻辑是有缺陷的。 我build议如下:

 Function IsIn(element, arr) As Boolean IsIn = False For Each x In arr If element = x Then IsIn = True Exit Function End If Next x End Function Sub Get_Stock_Quotes_from_Yahoo_Finance_API() Dim skippedSheets() skippedSheets = Array("Cover,Select Industry,bla bla") For Each Sh In ActiveWorkbook.Worksheets If Not IsIn(Sh.Name, skippedSheets) Then ' ... process Sh End If Next Sh End Sub 

现在你有所有要排除在一个地方的名单(数组赋值),只有在当前表名不是该数组的元素的情况下才会执行内部代码块。

错误的第二个来源:你已经开始限定范围了(比如在Set head = Sht.Range("A2") )。 在另外两个地方做同样的事情
Set rng = Sht.Range(head.Offset(1, 0), head.Offset(1, 0).End(xlDown))

Set rng = Sht.Range(head.Offset(0, 1), head.Offset(0, 1).End(xlToRight))

最后,你不必activate表。 您使用Sht对象和合格的范围。
Dim I as Integer是未使用的。