2016-05-10 6 views
2

私はセル範囲がC6:C10です。私はVBAコードを使用して、この範囲のセルにif文を適用しようとしています。現在、私のコードは、最初のセル(C6)のif文の出力を受け取り、セルC7:C10の値を複製します。 ifステートメントが正しいです、私はちょうど列のセルの範囲にそれを適用する方法がわかりません。VBAを使用してif文をセル範囲に適用する

Sub Cleanup() 
Dim Segment As String 
Dim i As Integer 
Segment = ActiveCell(6, 3).Value 
For i = 6 To 10 
    If Right(Left(Segment, 6), 1) = "/" Then 
     ActiveCell(i, 3).Value = Left(Segment, 5) 
    Else 
     ActiveCell(i, 3).Value = Left(Segment, 6) 
    End If 
Next i 
End Sub 
+0

変更 'ActiveCell'に' Cells'。 – Ambie

答えて

1

あなたが代わりのActiveCellの細胞を使用する場合は7から10に行くことかそうでなければ、元のセルだけでなく、C7を過剰書きますあなたのループを変更する必要がありますことを除いては、問題ないはずです。 C10。

Sub Cleanup() 
Dim Segment As String 
Dim i As Integer 
Segment = Cells(6, 3).Value 
For i = 7 To 10 
    If Right(Left(Segment, 6), 1) = "/" Then 
     Cells(i, 3).Value = Left(Segment, 5) 
    Else 
     Cells(i, 3).Value = Left(Segment, 6) 
    End If 
Next i 
End Sub 
1
Sub Cleanup() 
    Dim Segment As String 
    Dim i As Integer 
    Segment = Cells(i, 3).Value 
    For i = 7 To 10 
     If Right(Left(Segment, 6), 1) = "/" Then 
      cells(i, 3).Value = Left(Segment, 5) 
     Else 
      Cells(i, 3).Value = Left(Segment, 6) 
     End If 
    Next i 
End Sub 
+0

私のコードをこのコードに変更すると、エラーコード400が表示されます。私のコードは、存在しないか、もはや存在しないものを参照していると思います。なぜ6を "私は4行目でこれを引き起こしました。ちょうど明確にするために、私はC6の下にあるものを複製するつもりはない、私はちょうどifステートメントをC6に続くセルに適用したい – Davey

0

ここ3単純化のために(最初のよりシンプル最後ビーイング)で、可能なコード(他の多くのうち):

Option Explicit 

Sub Cleanup() 
    Dim Segment As String 
    Dim i As Integer 

    For i = 6 To 10 
     Segment = Cells(i, 3).Value '<== Cells(i, 3) is the current cell as per the current row (i) 
     If Mid(Segment, 6, 1) = "/" Then 
      Cells(i, 3).Value = Left(Segment, 5) 
     Else 
      Cells(i, 3).Value = Left(Segment, 6) 
     End If 
    Next i 
End Sub 


Sub Cleanup2() 
    Dim i As Integer 

    For i = 6 To 10 
     With Cells(i, 3) 'avoid repetitions (and a variable, too) by using 'With' keyword and implying 'Cells(i, 3)' preceeds every dot (".") till next 'End With" statement 
      If Right(Left(.Value, 6), 1) = "/" Then 
       .Value = Left(.Value, 5) 
      Else 
       .Value = Left(.Value, 6) 
      End If 
     End With 
    Next i 
End Sub 


Sub Cleanup3() 
    Dim i As Integer 

    For i = 6 To 10 
     With Cells(i, 3) 
      .Value = Left(.Value, IIf(Mid(.Value, 6, 1) = "/", 5, 6)) ' use Iif function to avoid multiple lines. Also use 'Mid' function in lieu of 'Right(Left(..))' 
     End With 
    Next i 
End Sub 
関連する問題