【问题标题】:Issue with For LoopsFor 循环的问题
【发布时间】:2014-03-05 17:50:49
【问题描述】:

为什么这不起作用?基本上,我在单个单元格中有一个列表,我想拆分以“sec”结尾的字符串,以及不通过将它们复制到不同列中的字​​符串。

Sub test_if()
   For i = 1 To 300
      Cells(i, 2).Select
      If Right(Cells(i, 2), 3) = "SEC" Then
         ActiveCell.Select
         Selection.Copy
         Cells(i, 3).Select
         ActiveSheet.Paste
      End If

      If Right(Cells(i, 2), 3) <> "SEC" Then
         ActiveCell.Select
         Selection.Copy
         'Cells(i, 4).Select
         ActiveCell.Offset(i - 1, 2).Select
         ActiveSheet.Paste
      End If
   Next i    
   Cells(1, 1).Select
End Sub

【问题讨论】:

    标签: vba excel for-loop offset


    【解决方案1】:

    试试这个:

    Sub test_if()
        Dim i As Integer
    
        For i = 1 To 300
            With Cells(i, 2)
                If UCase(Right(.Value, 3)) = "SEC" Then
                   .Offset(, 1).Value = .Value
                Else
                   .Offset(i - 1, 2).Value = .Value
                End If
            End With
       Next i
    End Sub
    

    也请阅读how to avoid using Select/Active statements

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2013-07-14
      • 2021-05-10
      • 2012-09-20
      • 2018-12-15
      相关资源
      最近更新 更多