【问题标题】:excel vba select value in row, which was selected through for eachexcel vba在行中选择值,这是通过为每个选择的
【发布时间】:2015-09-04 18:08:59
【问题描述】:

我正在尝试逐行循环浏览我的工作表rngSAP 的范围。如果该行中单元格 2 的值等于字符串,我想使用该行的一些数据。这就是我所拥有的,但我收到type not matched 错误。

with shtSAP
    Set rngSAP = .Range(.Cells(1, 1), .Cells(rowsSAP, colsSAP))
    For Each cellSAP In rngSAP.Rows
        If cellSAP(2).Value = "03" Then
            MsgBox (cellSAP(5))
        End If
    Next
end with

谁能帮我写出正确的代码?

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    这是你正在尝试的吗?

    With shtSAP
        Set rngSAP = .Range(.Cells(1, 1), .Cells(rowsSAP, colsSAP))
    
        For Each cellSAP In rngSAP.Rows
            If Cells(cellSAP.Row, 2).Value = "03" Then
                MsgBox Cells(cellSAP.Row, 2).Value
            End If
        Next
    End With
    

    完整示例

    Sub Sample()
        Dim shtSAP As Worksheet
        Dim rngSAP As Range
        Dim cellSAP
        Dim rowsSAP As Long, colsSAP As Long
    
        Set shtSAP = ActiveSheet
    
        rowsSAP = 5: colsSAP = 5
    
        With shtSAP
            Set rngSAP = .Range(.Cells(1, 1), .Cells(rowsSAP, colsSAP))
    
            For Each cellSAP In rngSAP.Rows
                'Debug.Print Cells(cellSAP.Row, 2).Address
                If Cells(cellSAP.Row, 2).Value = "03" Then
                    MsgBox Cells(cellSAP.Row, 2).Value
                End If
            Next
        End With
    End Sub
    

    或者这个?

    Sub Sample()
        Dim shtSAP As Worksheet
        Dim rngSAP As Range
        Dim cellSAP
        Dim rowsSAP As Long, colsSAP As Long
    
        Set shtSAP = ActiveSheet
    
        rowsSAP = 5: colsSAP = 5
    
        With shtSAP
            Set rngSAP = .Range(.Cells(1, 1), .Cells(rowsSAP, colsSAP))
            For Each cellSAP In rngSAP.Rows
                'Debug.Print cellSAP.Cells(, 2).Address
    
                If cellSAP.Cells(, 2).Address = "03" Then
                    MsgBox Cells(cellSAP.Row, 2).Value
                End If
            Next
        End With
    End Sub
    

    【讨论】:

    • 您的第一个解决方案是,我需要的。感谢您的提示。但我有一个补充。 If cellSAP.Rows(2).Value = "03" 对我来说似乎比 If Cells(cellSAP.Row,2).Value = "03" 更干净,或者这两个是等价的吗?
    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多