[英]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.例如,如果范围对象是
A1:D5
我想遍历A4, B4, C4, D4
值。
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.
编辑:添加了在第 4 行显示单元格的条件。
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.