将if语句应用于使用VBA的单元格范围

我有一个小范围的细胞,C6:C10。 我试图应用一个if语句使用VBA代码的这个单元格范围。 目前,我的代码获取第一个单元格(C6)的if语句的输出,并为单元格C7:C10复制该值。 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 

如果你使用Cells而不是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 
 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 

这里有三个可能的代码(按照简单的顺序排列)(最后一个比第一个简单):

 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