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

Excel 使用VBA将if语句应用于单元格范围,excel,vba,if-statement,range,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,

我有一个小范围的细胞,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

如果您使用单元格而不是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
这里有三个(在许多其他代码中)可能的代码,按简单顺序排列(最后一个代码比第一个代码更简单):

选项显式
次级清理()
将段变暗为字符串
作为整数的Dim i
对于i=6到10

段=单元格(i,3)。值“将
ActiveCell
更改为
Cells
。因此,在将代码更改为此代码后,它现在给我的错误代码为400。我猜我的代码指的是不存在或不再存在的东西,我不确定为什么在第4行将6改为“I”会导致这种情况。我只是想澄清一下,我并不是想向下复制C6单元中的内容,我只是想让if语句应用于C6单元后面的单元
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