简体   繁体   中英

Excel VBA Loop Dynamic Range

I'm wanting to analyse the cells in column B based on the length of column C and return my values to column A.

The following code works great for sheet1, however in subsequent sheets the range doesn't change to reflect the length of column C. In other words, for all subsequent sheets though the values returned are correct, they are only populated up to the length of column C in sheet1.

Anyone know why my loop is not working to reflect the dynamic range of column C, please?

Sub SetValuesAllSheets()
    Dim wSht As Worksheet
    Dim myRng As Range
    Dim allwShts As Sheets
    Dim cel As Range

    Dim LR As Long
    LR = Range("C" & Rows.Count).End(xlUp).Row


    Set allwShts = Worksheets
    For Each wSht In allwShts
        Set myRng = wSht.Range("B1:B" & LR)
        For Each cel In myRng
            If cel.Interior.Color = RGB(255, 0, 0) Then
                cel.Offset(0, -1) = "colour"
            ElseIf IsNumeric(cel) = True Then
                cel.Offset(0, -1) = "number"
            End If
        Next cel
    Next wSht
End Sub  

Indeed, LR is determined for the active sheet. You need to insert it in the loop to get it work:

Sub SetValuesAllSheets()
    Dim wSht As Worksheet
    Dim myRng As Range
    Dim allwShts As Sheets
    Dim cel As Range

    Dim LR As Long

    Set allwShts = Worksheets
    For Each wSht In allwShts
        LR = wSht.Range("C" & Rows.Count).End(xlUp).Row
        Set myRng = wSht.Range("B1:B" & LR)
        For Each cel In myRng
            If cel.Interior.Color = RGB(255, 0, 0) Then
                cel.Offset(0, -1) = "colour"
            ElseIf IsNumeric(cel) = True Then
                cel.Offset(0, -1) = "number"
            End If
        Next cel
    Next wSht
End Sub

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM