2015-01-17 28 views
0

我想创建一个宏为这个公式:只有一个值显示在目标列

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应该是“平台”时,它仍然显示“Trans-ship”。我非常感谢任何帮助!

回答

0

它在第一个单元格中停止,因为您的的Exit For部分为If Statement
因为您试图检查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上的值。

+0

工程就像一个魔术!感谢所有3个代码! –

相关问题