簡體   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