目标列中仅显示一个值

Only One Value Shows In Target Column

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

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

问题是将值填充到 B 列中的单元格的操作在第一个单元格 B2 处停止。而当我有i=8时,B8应该是"Platform",它仍然显示"Trans-ship"。我真的很感激任何帮助!!

它在第一个单元格中停止,因为您在 If StatementElse 部分有 Exit For
您没有得到预期的结果,因为您试图检查 Cell(i, 1) 的值是否等于字符串 =IF(LEFT(i,1)=""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

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

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

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

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

所有此示例仅显示 B 列中的值。HTH。