2015-09-04 128 views
0

我試圖循環通過我的工作表rngSAP行的範圍。如果該行中的單元格2的值等於一個字符串,我想使用該行的一些數據。這是我的,但我得到type not matched錯誤。excel vba在行中選擇值,這是通過選擇每個

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 

任何人都可以幫我解決正確的代碼嗎?

回答

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 

OR這也許?

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 
+0

你的第一個解決方案就是我所需要的。感謝提示。但我有一個補充。 '如果cellSAP.Rows(2).Value =「03」'看起來比我更清潔,比'If Cells(cellSAP.Row,2).Value =「03」'還是這兩個等價的? – Kazschuri