简体   繁体   中英

Select range of cells based on 1 cell value

I am trying to figure out a VBA to select range of cells in same row based on a value in a cell. Example: let's say A1 cell has "5" as the cells value then it will select the 5 adjacent cells (B1:F1) and enter "OK" to those 5 cells Then then VBA will keep checking A2 on wards for value n do the same as above but if it found first blank cell in column A then the VBA stop

The following will check for the last row with data on Column A and then it will check each row to verify that the value held in Column A is numeric, then it will loop that many times across Columns, populating cells with "OK":

Sub ColumnALoop()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
For i = 1 To LastRow
'loop through Rows
    If IsNumeric(ws.Cells(i, 1).Value) Then ws.Range("B" & i).Resize(, ws.Cells(i, 1).Value).Value = "OK"
    'verify the value in Column A is numeric then enter OK in relevant cells
Next i
End Sub

Including a Worksheet_Change Event:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:A")) Is Nothing Then
'check if any changes have happened on Column A
    For Each c In Target
        If c.Column = 1 Then
        'ensure that we are looking at Column A as Target could include variable size ranges
            If IsNumeric(c) And c.Value <> "" Then Range("B" & c.Row).Resize(, c.Value).Value = "OK"
            'if value is numeric and not blank then enter "OK"
        End If
    Next c
End If
End Sub

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