简体   繁体   中英

How to loop through a specific column in each row for a range object VBA?

How to loop through range object for each row for a specific column. For instance, if range object is A1:D5 I want to loop through A4, B4, C4, D4 values.

When I try

Set ranges = Application.InputBox(Title:="Select the Range", Type:=8)

For Each r In ranges.Rows
    Msgbox r(1,4) 
Next r

It trows me an error.

Try below codes

Sub Loop4Row()
Dim r As Long, Ranges As Range

Set Ranges = Application.InputBox("Select the Range", Type:=8)
    For r = Application.Min(Ranges.Column) To Application.Max(Ranges.Columns)
        MsgBox Cells(4, r)
    Next r

End Sub

Try this. Edit: Added condition for displaying cells on 4th row.

Set Ranges = Application.InputBox(Prompt:="Select the Range", Title:="Select the Range", Type:=8)

For Each r In Ranges
  If r.Row = 4 Then
    MsgBox r.Value
  End If
Next r

Loop Through Cells of a Row

Short

Dim r as Range
For Each r In ranges.Rows(4).Cells
    Msgbox r.Address, r.Value
Next r

' or 

Dim r As Range, rg As Range
Set rg = ranges.Rows(4)
For Each r in rg.Cells
    Msgbox r.Address, r.Value
Next r

Long

Option Explicit

Sub LoopThroughTheFourthRow()
    
    Const sTitle As String = "Loop Through the Fourth Row"
    Const sRow As Long = 4
    
    ' Determine the parameter of the 'Default' argument.
    Dim dAddress As String
    If TypeName(Selection) = "Range" Then
        dAddress = Selection.Address
    Else
        dAddress = "$A$1"
    End If
     
    ' Input.
    On Error Resume Next
    Dim srg As Variant
    Set srg = Application.InputBox(Prompt:="Select a range", _
        Title:=sTitle, Default:=dAddress, Type:=8)
    On Error GoTo 0
    
    ' Validate input (Canceled?).
    If TypeName(srg) <> "Range" Then
        MsgBox "You canceled.", vbExclamation, sTitle
        Exit Sub
    End If
    
    ' Validate input (too few rows).
    Dim srCount As Long: srCount = srg.Rows.Count
    If srCount < sRow Then
        MsgBox "There are only " & srCount & " rows in the range.", _
            vbExclamation, sTitle
        Exit Sub
    End If
    
    'Debug.Print srg.Address(0, 0)
    
    ' Loop through the cells of the one-row range.
    Dim sCell As Range
    For Each sCell In srg.Rows(sRow).Cells
        Debug.Print sCell.Address(0, 0), sCell.Value
    Next sCell

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