繁体   English   中英

如何遍历范围对象 VBA 的每一行中的特定列?

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

如何为特定列的每一行循环范围对象。 例如,如果范围对象是A1:D5我想遍历A4, B4, C4, D4值。

当我尝试

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

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

它告诉我一个错误。

试试下面的代码

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

试试这个。 编辑:添加了在第 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

循环遍历一行的单元格

短的

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

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.

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