+ Reply to Thread
Results 1 to 6 of 6

Loop through a DIM variable

Hybrid View

  1. #1
    Registered User
    Join Date
    02-04-2018
    Location
    Canberra, Australia
    MS-Off Ver
    2013
    Posts
    77

    Loop through a DIM variable

    Hi All,

    I need to loop through a series of worksheets and I have the worksheets DIMed As String so I can reference them.

    I can't get the loop to recognise the number of the assigned Worksheet.

    Sub LoopDIM()
    
    Dim ws1 As String
    Dim ws2 As String
    Dim ws3 As String
    Dim ws4 As String
    
    WS1 = "Tab1"
    WS2 = "Tab2"
    WS3 = "Tab3"
    WS4 = "Tab4"
    
    For i = 1 to 10
    
    Sheets(ws, i).Select
    Range("A1").select
    
    Next
    
    End Sub
    How do I get ws to equal the i?

    Any help appreciated

    Cheers

    Dean

  2. #2
    Valued Forum Contributor
    Join Date
    05-03-2022
    Location
    Halifax,Canada
    MS-Off Ver
    365
    Posts
    326

    Re: Loop through a DIM variable

    This will reference every sheet in the workbook that contains the code .

    Public Sub RefEachSheetInWkBk()
        Dim sh As Worksheet
        Dim cellValue As Variant
    
        For Each sh In ThisWorkbook.Sheets
            cellValue = sh.Range("A1").Value
        Next sh
    End Sub

    this code will loop thru specific named sheets
    Sub LoopDIM()
        Dim shName
        Dim cellValue As Variant
    
        Const SHEET_NAMES As String = "Tab1,Tab2,Tab3,Tab4"
    
        For Each shName In Split(SHEET_NAMES, ",")
            With Sheets(shName)
                .Range("A1").Value = "test"
                cellValue = .Range("A1").Value
            End With
        Next shName
    
    End Sub
    HERE'S EXCELLENT REFERENCE ON SUBJECT : https://docs.microsoft.com/en-us/off...lls-and-ranges

    if this code has helped please consider clicking "add reputation" , thx
    Last edited by nimrod1313; 08-31-2022 at 04:13 AM.

  3. #3
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2503
    Posts
    1,485

    Re: Loop through a DIM variable

    If you want to loop through specific sheets then you could use something like the below:
    Sub LoopDIM()
        Dim mSheets As Variant, i As Integer
        
        mSheets = Split("Tab1,Tab2,Tab3,Tab4", ",")
    
        For i = 0 To UBound(mSheets)
            Sheets(mSheets(i)).Range("A1") = "Hello World"
        Next
    End Sub
    Also no need for select, see how tha above can write to each sheet without selecting.
    If things don't change they stay the same

  4. #4
    Valued Forum Contributor
    Join Date
    05-03-2022
    Location
    Halifax,Canada
    MS-Off Ver
    365
    Posts
    326

    Re: Loop through a DIM variable

    This solution loops thru each sheet name AND checks that the sheet exists before accessing it.
    If the sheet does not exist the macro tells you so and exits the process.
    This example uses a re-usable function to perform a "Safe Set" (ie. safeSetSheet)
    In MY ACTUAL CODE I almost always use the "Safe Set" method
    Without a "Safe Set" method your macro will crash if sheet does not exist

    Sub LoopDIM()
        Dim shName
        Dim cellValue As Variant
        Dim currSh As Worksheet
    
        Const SHEET_NAMES As String = "Tab1,Tab2,Tab3,Tab4"
    
        For Each shName In Split(SHEET_NAMES, ",")
        
            Set currSh = safeSetSheet(ThisWorkbook.Name, CStr(shName))
            If currSh Is Nothing Then Exit Sub
            With currSh
                .Range("A1").Value = "test"
                cellValue = .Range("A1").Value
            End With
        Next shName
    
    End Sub
    
    Public Function safeSetSheet(wkBkName As String, sheetName As String) As Worksheet
        Dim wkBk As Workbook
        Dim wkSh As Worksheet
        Dim errMsg As String, reason As String
    
        Const REASON_PREFIX As String = "Could not locate required "
    
        On Error Resume Next
        Set wkBk = Workbooks(wkBkName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "workbook."
            GoTo errHandler
        End If
    
        Set safeSetSheet = wkBk.Sheets(sheetName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "worksheet."
            GoTo errHandler
        End If
    
        Exit Function
    errHandler:
        errMsg = reason & vbNewLine
        errMsg = errMsg & "Workbook:" & vbTab & wkBkName & vbNewLine
        errMsg = errMsg & "Worksheet:" & vbTab & sheetName & vbNewLine
        MsgBox errMsg, vbCritical, "Process Aborted"
    End Function
    HERE'S EXCELLENT REFERENCE ON SUBJECT : https://docs.microsoft.com/en-us/off...lls-and-ranges

    if this code has helped please consider clicking "add reputation" , thx
    Last edited by nimrod1313; 08-31-2022 at 04:16 AM.

  5. #5
    Valued Forum Contributor
    Join Date
    05-03-2022
    Location
    Halifax,Canada
    MS-Off Ver
    365
    Posts
    326

    Re: Loop through a DIM variable

    Accessing many sheets at once
    This example uses a re-usable function to perform a "Safe Set" (ie. safeSetSheet)
    In MY ACTUAL CODE I almost always use the "Safe Set" method
    Without a "Safe Set" method your macro will crash if sheet does not exist

    WITH SAFESET
    Sub accessManySheets()
        Dim AccSh As Worksheet, CostSh As Worksheet, InvSh As Worksheet
        
        'set reference to accounting sheet in the workbook that contains macro
        Set AccSh = safeSetSheet(ThisWorkbook.Name, "Sheet1")
        If AccSh = Nothing Then Exit Sub
        
        'set reference to cost sheet in the active workbook
        Set CostSh = safeSetSheet(ActiveWorkbook.Name, "Sheet2")
        If CostSh = Nothing Then Exit Sub
    
        
        'set reference to Invoice sheet in workbook called book1
        Set InvSh = safeSetSheet(Workbooks("book1.xlsx"), "Sheet2")
        If InvSh = Nothing Then Exit Sub
        
        ' assign Invoice sheet value from Cost sheet
        InvSh.Range("A1").Value = CostSh.Range("B1").Value
    
    End Sub
    
    Public Function safeSetSheet(wkBkName As String, sheetName As String) As Worksheet
        Dim wkBk As Workbook
        Dim wkSh As Worksheet
        Dim errMsg As String, reason As String
    
        Const REASON_PREFIX As String = "Could not locate required "
    
        On Error Resume Next
        Set wkBk = Workbooks(wkBkName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "workbook."
            GoTo errHandler
        End If
    
        Set safeSetSheet = wkBk.Sheets(sheetName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "worksheet."
            GoTo errHandler
        End If
    
        Exit Function
    errHandler:
        errMsg = reason & vbNewLine
        errMsg = errMsg & "Workbook:" & vbTab & wkBkName & vbNewLine
        errMsg = errMsg & "Worksheet:" & vbTab & sheetName & vbNewLine
        MsgBox errMsg, vbCritical, "Process Aborted"
    End Function

    WITHOUT SAFESET
    NOTE: Without a "Safe Set" method your macro will crash if sheet does not exist
    Sub accessManySheets()
        Dim AccSh As Worksheet, CostSh As Worksheet, InvSh As Worksheet
        
        'set reference to accounting sheet in the workbook that contains macro
        Set AccSh = ThisWorkbook.Sheets("Sheet1")
        
        'set reference to cost sheet in the active workbook
        Set CostSh = ActiveWorkbook.Sheets("Sheet2")
       
        'set reference to Invoice sheet in workbook called book1
        Set InvSh = Workbooks("book1.xlsx").Sheets("Sheet2")
        
        ' assign Invoice sheet value from Cost sheet
        InvSh.Range("A1").Value = CostSh.Range("B1").Value
    
    End Sub
    HERE'S EXCELLENT REFERENCE ON SUBJECT : https://docs.microsoft.com/en-us/off...lls-and-ranges

    if this code has helped please consider clicking "add reputation" , thx
    Last edited by nimrod1313; 08-31-2022 at 04:18 AM.

  6. #6
    Valued Forum Contributor
    Join Date
    05-03-2022
    Location
    Halifax,Canada
    MS-Off Ver
    365
    Posts
    326

    Re: Loop through a DIM variable

    Four demos on referencing the same sheet multiple times ( from worst to best)

    Public Sub demo1()
        Sheets("Sheet1").Range("A1").Value = "Test"
        Sheets("Sheet1").Range("A2").Value = "Test"
        Sheets("Sheet1").Range("A3").Value = "Test"
    End Sub
    Public Sub demo2()
        With Sheets("Sheet1")
            .Range("A1").Value = "Test"
            .Range("A2").Value = "Test"
            .Range("A3").Value = "Test"
        End With
    End Sub
    note the practice of giving the sheet Var a meaningful name that helps indicate intent (eg. its the target sheet )

    Public Sub demo3()
    Dim targetSh As Worksheet
    
    Set targetSh = Sheets("Sheet1")
    
        With targetSh
            .Range("A1").Value = "Test"
            .Range("A2").Value = "Test"
            .Range("A3").Value = "Test"
        End With
    End Sub
    Public Sub demo4()
    Dim targetSh As Worksheet
    
    Set targetSh = safeSetSheet(ThisWorkbook.Name, "Sheet1")
    If targetSh Is Nothing Then Exit Sub
    
        With targetSh
            .Range("A1").Value = "Test"
            .Range("A2").Value = "Test"
            .Range("A3").Value = "Test"
        End With
    End Sub
    
    Public Function safeSetSheet(wkBkName As String, sheetName As String) As Worksheet
        Dim wkBk As Workbook
        Dim wkSh As Worksheet
        Dim errMsg As String, reason As String
    
        Const REASON_PREFIX As String = "Could not locate required "
    
        On Error Resume Next
        Set wkBk = Workbooks(wkBkName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "workbook."
            GoTo errHandler
        End If
    
        Set safeSetSheet = wkBk.Sheets(sheetName)
        If Err.Number > 0 Then
            reason = REASON_PREFIX & "worksheet."
            GoTo errHandler
        End If
    
        Exit Function
    errHandler:
        errMsg = reason & vbNewLine
        errMsg = errMsg & "Workbook:" & vbTab & wkBkName & vbNewLine
        errMsg = errMsg & "Worksheet:" & vbTab & sheetName & vbNewLine
        MsgBox errMsg, vbCritical, "Process Aborted"
    End Function
    if this code has helped please consider clicking "add reputation" , thx
    Last edited by nimrod1313; 08-31-2022 at 12:48 PM.

+ 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. [SOLVED] Error handling not working in "vba object variable or with block variable not set" in Loop
    By caabdul in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 11-23-2019, 06:40 PM
  2. [SOLVED] Can i make the column I want to loop a variable? (i,VARIABLE) instead of (i,2)
    By trenzalore888 in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 01-31-2017, 12:48 PM
  3. [SOLVED] correctly 'wording' a for/next loop using a variable counter and variable filter
    By DBoyd121 in forum Excel Formulas & Functions
    Replies: 6
    Last Post: 07-14-2016, 06:13 PM
  4. [SOLVED] VB Loop different variables and stop variable to find a new variable..
    By feroguz in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 11-14-2014, 04:54 PM
  5. Replies: 6
    Last Post: 12-21-2012, 08:03 AM
  6. Why did an inner loop variable start overwriting the outer loop range suddenly?
    By 111StepsAhead in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-16-2012, 03:24 PM
  7. For Each ... Next loop - need to reference the loop variable
    By neonx3@yahoo.ca in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 07-13-2006, 01:15 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