使用VBA将if语句应用于单元格区域

时间:2016-05-10 14:58:28

标签: excel vba if-statement range

我有一小部分细胞,C6:C10。我尝试使用VBA代码将if语句应用于此范围的单元格。目前,我的代码获取第一个单元格(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

3 个答案:

答案 0 :(得分:1)

如果你使用Cell而不是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 :(得分: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

答案 2 :(得分:0)

这里有三个(其他许多)可能的代码,按简单顺序排列(最后一个比第一个更简单):

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