+ Reply to Thread
Results 1 to 10 of 10

trouble with variable sheet name

Hybrid View

  1. #1
    Registered User
    Join Date
    06-13-2014
    Posts
    23

    trouble with variable sheet name

    Hi all,
    I have a workbook that downloads information from the internet and places it on a spreadsheet. That part works fine, but I am also trying to include a filter in the process. I am using a string variable (that may not be the correct term), that is used in the url and also is the name of the sheet where the filtered data is supposed to end up. Abbreviated code as follows (i did not include the query part of the code):

    Sub GetData()
    
    Dim strFin(1 To 3) As String
        strFin(1) = "basicmaterials"
        strFin(2) = "consumergoods"
        strFin(3) = "financial"
    
    For Z = 1 To 3
    
    Dim RowCt As Integer
    Dim RowTot As Variant
    
    Sheets("Raw").Activate
    RowTot = ActiveSheet.UsedRange.Rows.Count
    
    For RowCt = 2 To RowTot
            If (Sheets("Raw").Cells(RowCt, 7).Value < 0 And Sheets("Raw").Cells(RowCt, 5).Value > 0 And _
                Sheets("Raw").Cells(RowCt, 4).Value > 0) Then
                    Range("A" & RowCt & ":" & "K" & RowCt).Select
            Selection.Copy Destination:=Sheets(strFin(Z)).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
        End If
    Next RowCt
    
    Next Z
    
    End Sub
    I am getting a Run-time error '9' Subscript out of range in the red line of code.

    This worked when I tested it with a specific sheet name (e.g. "basicmaterials"), but it doesn't this way.

    Thanks.

  2. #2
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2411
    Posts
    26,729

    Re: trouble with variable sheet name

    That error can be caused by two things, and it's more likely the second thing. The first thing is that strFin(Z) is undefined because Z is not a valid index. However, you set elements 1, 2, and 3 above, and the loop goes from 1 to 3, so that part looks OK. This error can also be caused if strFin(Z) does not return an existing sheet name. So I'll bet one of these sheets doesn't exist (if you think they all three exist, double check for typos on the tabs). Note that this is the name that the user sees on the tab.

    "basicmaterials"
    "consumergoods"
    "financial"

    I see another problem too, in that line of code, which may not cause a runtime error but will cause a bug. An unqualified reference to Rows will refer to the active sheet if this is a Module, or the sheet containing the code if it's a Sheet Module. Either one will be wrong for your situation. You need to qualify Rows:

    Selection.Copy Destination:=Sheets(strFin(Z)).Range("A" & Sheets(strFin(Z)).Rows.Count).End(xlUp).Offset(1, 0)
    Jeff
    | | |會 |會 |會 |會 | |:| | |會 |會
    Read the rules
    Use code tags to [code]enclose your code![/code]

  3. #3
    Forum Guru
    Join Date
    03-02-2006
    Location
    Los Angeles, Ca
    MS-Off Ver
    WinXP/MSO2007;Win10/MSO2016
    Posts
    12,925

    Re: trouble with variable sheet name

    Also, verify that the actual tab names don't have leading/trailing spaces
    Ben Van Johnson

  4. #4
    Forum Expert
    Join Date
    07-31-2010
    Location
    California
    MS-Off Ver
    Excel 2007
    Posts
    4,070

    Re: trouble with variable sheet name

    Here is a way that you can check to see what sheet names don't match up. Just run the code:

    Sub Show_Missing_Sheets()
    Dim Z As Integer
    Dim strSheet As String
    Dim strFin(1 To 3) As String
    strFin(1) = "basicmaterials"
    strFin(2) = "consumergoods"
    strFin(3) = "financial"
        
        
    For Z = 1 To 3
    
    If Not Evaluate("=ISREF('" & strFin(Z) & "'!A1)") = True Then
        strSheet = strSheet & " " & strFin(Z) 'sheet names that weren't found
    End If
    
    Next Z
    
    MsgBox (strSheet)
    
    End Sub

  5. #5
    Registered User
    Join Date
    06-13-2014
    Posts
    23

    Re: trouble with variable sheet name

    Thanks for your responses. I ran the code suggested by stnkynts and got no matches, so I assume that if i did have an errant space before or after the name that it would have showed that. However, just to be sure I also checked manually for extra spaces. All good on that count.

    I tried the modification suggested by 6StringJazzer but ended up with the same Run-time error. My thinking then was to break that line down to see where the error is occuring. Modified as follows:

    For RowCt = 2 To RowTot
            If (Sheets("Raw").Cells(RowCt, 7).Value < 0 And Sheets("Raw").Cells(RowCt, 5).Value > 0 And _
                Sheets("Raw").Cells(RowCt, 4).Value > 0) Then
                    Range("A" & RowCt & ":" & "K" & RowCt).Select
            Selection.Copy
            Sheets(strFin(Z)).Activate
            Range("A" & Sheets(strFin(Z)).Rows.Count).End(xlUp).Offset(1, 0).Select
            ActiveSheet.Paste
        End If
    Next RowCt
    Run-time error occurred on red line. I also tried: Dim sheetName as String and then sheetName = strFin(Z) thinking that maybe that would push it through, but alas same result.

    I honestly cannot see what is wrong with that part. Still stumped.

  6. #6
    Forum Guru
    Join Date
    03-02-2006
    Location
    Los Angeles, Ca
    MS-Off Ver
    WinXP/MSO2007;Win10/MSO2016
    Posts
    12,925

    Re: trouble with variable sheet name

    Runs w/o error:
    Option Explicit
    
    Sub GetData()
        Dim strFin(1 To 3) As String
            strFin(1) = "basicmaterials"
            strFin(2) = "consumergoods"
            strFin(3) = "financial"
        Dim RowCt As Integer, Z
        Dim RowTot As Variant
        
        With Sheets("Raw")
            RowTot = .UsedRange.Rows.Count
            For Z = 1 To 3
            
                For RowCt = 2 To RowTot
                    If (.Cells(RowCt, 7).Value < 0 And .Cells(RowCt, 5).Value > 0 And .Cells(RowCt, 4).Value > 0) Then
                        .Range("A" & RowCt & ":" & "K" & RowCt).Copy _
                            Destination:=Sheets(strFin(Z)).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
                    End If
                Next RowCt
            
            Next Z
        End With 'raw
    
    End Sub

  7. #7
    Registered User
    Join Date
    06-13-2014
    Posts
    23

    Re: trouble with variable sheet name

    Hi protonLeah,

    I tried this more or less, but got the same error. The modification I had to make was because the the Next Z statement actually needs to be outside the With statement. Perhaps I should have done this earlier, but here is the code in it's entirety:

    Sub GetFinvizData()
    
    Dim Z As Integer
    Dim strFin(1 To 8) As String
        strFin(1) = "basicmaterials"
        strFin(2) = "consumergoods"
        strFin(3) = "financial"
        strFin(4) = "healthcare"
        strFin(5) = "industrialgoods"
        strFin(6) = "services"
        strFin(7) = "technology"
        strFin(8) = "utilities"
    Dim RowCt As Integer
    Dim RowTot As Variant
    
    For Z = 1 To 8
    
    'Delete existing data
    
    Sheets("Raw").Activate
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.ClearContents
    
    'Download Sector Stock Data
    
    strFin(Z) = "http://finviz.com/export.ashx?v=151&f=sec_" & strFin(Z) & ",sh_avgvol_o500,sh_opt_optionshort,sh_price_o10&ft=4&o=industry&c=1,2,4,42,43,44,45,46,47,65,68"
    QueryQuote:
                With Sheets("Raw").QueryTables.Add(Connection:="URL;" & strFin(Z), Destination:=Sheets("Raw").Range("a1"))
                    .BackgroundQuery = True
                    .TablesOnlyFromHTML = False
                    .Refresh BackgroundQuery:=False
                    .SaveData = True
                End With
    
    Sheets("Raw").Range("a1").CurrentRegion.TextToColumns Destination:=Sheets("Raw").Range("a1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=True, Space:=False, other:=True, OtherChar:=",", FieldInfo:=Array(1, 2)
           
    Sheets("Raw").Columns("A:B").ColumnWidth = 12
    Range("A1").Select
    
    'Filters bullish potential trades based on:
        '-Week and month performance positive
        '-Half performance negative
        
        With Sheets("Raw")
            RowTot = .UsedRange.Rows.Count
                    
                For RowCt = 2 To RowTot
                    If (.Cells(RowCt, 7).Value < 0 And .Cells(RowCt, 5).Value > 0 And .Cells(RowCt, 4).Value > 0) Then
                        .Range("A" & RowCt & ":" & "K" & RowCt).Copy _
                            Destination:=Sheets(strFin(Z)).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
                    End If
                Next RowCt
            
        End With
    Next Z
    
    End Sub
    I think the With statement is the way to go, but it resulted in the same error when the Next Z was outside of the last With. Again the query works fine. The idea is that "Raw" is the dump sheet for the data before filtering. Once the filter is complete, then "Raw" is cleared and the next set of data is brought in and will run through the same filter and placed on the sheet with the sector name. Ultimately there will be approximately 6 different filters run on the data before I get to the Next Z. I have not written the other filters yet, since I think if I can get one to work the others will follow suit.

    Thanks.

  8. #8
    Registered User
    Join Date
    06-13-2014
    Posts
    23

    Re: trouble with variable sheet name

    Ok I am an idiot. As I was reviewing my last post, I noticed that I set the value of strFin(z) as the url. Works fine when i use a different string for the url. I am kind of surprised that it didn't kick out an error on that debacle. Anyway, thanks all for your help.

  9. #9
    Forum Guru
    Join Date
    03-02-2006
    Location
    Los Angeles, Ca
    MS-Off Ver
    WinXP/MSO2007;Win10/MSO2016
    Posts
    12,925

    Re: trouble with variable sheet name

    1. strFin(1) = "basicmaterials"
    Then you do:

    strFin(Z) = "http://finviz.com/export.ashx?v=151&f=sec_" & strFin(Z) & ",sh_avgvol_o500,sh_opt_optionshort,sh_price_o10&ft=4&o=industry&c=1,2,4,42,43,44,45,46,47,65,68"

    which results in:

    "http://finviz.com/export.ashx?v=151&f=sec_basicmaterials,sh_avgvol_o500,sh_opt_optionshort,sh_price_o10&ft=4&o=industry&c=1,2,4,42,43,44,45,46,47,65,68"

    which cannot be a tab name:
    Destination:=Sheets(strFin(Z)).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

    So you need to use another variable to hold the url. It doesn't have to be an array, just a string var:
    URLStr = "http://finviz.com/export.ashx?v=151&f=sec_" & strFin(Z) & ",sh_avgvol_o500,sh_opt_optionshort,sh_price_o10&ft=4&o=industry&c=1,2,4,42,43,44,45,46,47,65,68"

    ... Connection:="URL;" & URLStr ...
    Etc.

  10. #10
    Registered User
    Join Date
    06-13-2014
    Posts
    23

    Re: trouble with variable sheet name

    Exactly. Thanks protonLeah. used strFinSite as string for url. pretty much how i felt when i saw it.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 1
    Last Post: 11-08-2013, 10:37 PM
  2. [SOLVED] Trouble setting workbook variable
    By TC1980 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 08-30-2013, 05:52 AM
  3. Trouble passing variable to another function
    By Jasmith in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 04-28-2011, 10:15 AM
  4. [SOLVED] Trouble with module wide variable
    By saabman in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 03-10-2009, 05:41 AM
  5. [SOLVED] trouble comparing a value in a text box with a variable
    By JasonK in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 04-10-2006, 01:00 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1