目标列中只显示一个值

时间:2015-01-17 04:30:35

标签: excel vba excel-vba

我正在尝试为此公式创建一个宏:

B2=IF(LEFT(A2,1)="1","Platform","Trans-ship") 

并且此公式继续向下到列A具有值的最后一行。 这是我的代码:

Sub Order_Type()
    Dim i As Long
    Dim j As Long
    i = 2
    Columns("B:B").Select
    Selection.Insert Shift:=xlToRight
    For j = i + 1 To ActiveSheet.UsedRange.Rows.Count
        If Cells(i, 1) = "=IF(LEFT(i,1)=""1""" Then
            Cells(i, 2) = "Platform"
        Else
            Cells(i, 2) = "Trans-ship"
            Exit For
        End If
    Next j
End Sub

问题是在第一个单元格(即B2)中,B列中的单元格填充值的操作。当我有i = 8,而B8应该是“平台”时,它仍然显示“Trans-ship”。我真的很感激任何帮助!!

1 个答案:

答案 0 :(得分:0)

它会在第一个单元格中停止,因为Exit For Else部分If Statement Cell(i, 1)。{你没有得到预期的结果,因为你'重新尝试检查Dim lr As Long With ActiveSheet lr = .Range("A" & .Rows.Count).End(xlUp).Row 'last row in A with value .Range("B2:B" & lr).Formula = "=IF(LEFT(A2,1)=""1"",""Platform"",""Trans-ship"")" .Range("B2:B" & lr).Value = .Range("B2:B" & lr).Value 'change to value End With 的值是否等于字符串 = IF(LEFT(i,1)="" 1""
试试这个:

Dim lr As Long, i As Long
With ActiveSheet
    lr = .Range("A" & .Rows.Count).End(xlUp).Row 'last row in A with value
    For i = 2 To lr
        If Left(.Cells(i, 1), 1) = "1" Then 
            .Cells(i, 2) = "Platform"
        Else
            .Cells(i, 2) = "Trans-ship
        End If
    Next
End With

如果你真的想使用你的逻辑,那么试试这个:

Dim lr As Long, i As Long
With ActiveSheet
    lr = .Range("A" & .Rows.Count).End(xlUp).Row 'last row in A with value
    For i = 2 To lr
        .Cells(i, 2) = IIf(Left(.Cells(i, 1), 1) = "1", "Platform", "Trans-ship")
    Next
End With

或者使用VBA的另一种变体是:

{{1}}

所有这个例子只显示B列上的值.HTH。