How to run a macro on some but not all sheets in a workbook?

前端 未结 2 1135
后悔当初
后悔当初 2021-01-28 14:40

I have a workbook that contains worksheets for each industry group in the S&P 500 and wrote the macro below to update all the stock information on them when I press a comman

相关标签:
2条回答
  • 2021-01-28 15:19

    Refering to Kevin's second code - now the exclusion logic is flawed. I suggest the following:

    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
    

    Now you have all sheet names which are to be excluded in one place (the array assignment) and the inner code block will only be executed if the current sheet name is not element of that array.

    Second source of error: you already started qualifying the ranges (like in Set head = Sht.Range("A2")). Do the same in 2 other places, with
    Set rng = Sht.Range(head.Offset(1, 0), head.Offset(1, 0).End(xlDown))
    and
    Set rng = Sht.Range(head.Offset(0, 1), head.Offset(0, 1).End(xlToRight))

    Last, you don't have to activate a sheet. You work with the Sht object and qualified ranges.
    Dim I as Integer is unused.

    0 讨论(0)
  • 2021-01-28 15:27

    Change

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

    To

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

    Don't forget your End If before Next Sht

    0 讨论(0)
提交回复
热议问题