代码不循环到需要更新的最后一个单元格

时间:2016-02-01 13:09:21

标签: vba excel-vba excel

我有几个需要更改的文本项。需要更改的数据仅显示在电子表格的B列中。代码有效,但在长列表中,不会发生最后一次有效更改。对于前者当它是最后一个填充的单元格并且需要更改时,“Roger”不会更新。实际上,我有大约12个IF Then语句。

我尝试插入循环并收到错误。

Sub Names2()
Dim aRow As Integer

For aRow = 1 To WorksheetFunction.CountA(Columns(2))

    If Cells(aRow, 2) = "Jay" Then
       Cells(aRow, 2) = "Jason"
    End If

    If Cells(aRow, 2) = "Steve" Then
       Cells(aRow, 2) = "Steven"
    End If

    If Cells(aRow, 2) = "Rog" Then
       Cells(aRow, 2) = "Roger"
    End If

    Next aRow

End Sub

3 个答案:

答案 0 :(得分:1)

试试这个。

Sub Names2()
Dim aRow As Long, FRowB As Long
Dim wk As Worksheet
Dim m As Long

Set wk=Sheet1         'Replace this with your Worksheet Number

m=wk.Rows.Count

FRowB = wk.Range("B" & m).End(xlUp).Row

For aRow = 1 To FRowB

    If Cells(aRow, 2) = "Jay" Then Cells(aRow, 2) = "Jason"

    If Cells(aRow, 2) = "Steve" Then Cells(aRow, 2) = "Steven"

    If Cells(aRow, 2) = "Rog" Then Cells(aRow, 2) = "Roger"


Next aRow

End Sub

答案 1 :(得分:1)

arow的值在整个代码中都是1,你需要递增它以将它移动到下一行,以便你更容易理解我不是为任务编写新代码而是修改你的代码

Sub Names2()

For aRow = 1 To WorksheetFunction.CountA(Columns(2))

If Cells(aRow, 2) = "Jay" Then
   Cells(aRow, 2) = "Jason"
aRow = aRow+1
End If

If Cells(aRow, 2) = "Steve" Then
   Cells(aRow, 2) = "Steven"
aRow = aRow+1
End If

If Cells(aRow, 2) = "Rog" Then
   Cells(aRow, 2) = "Roger"
aRow = aRow+1
End If

Next aRow

 End Sub

答案 2 :(得分:0)

此外,您可以在没有循环(更快)的情况下执行此操作:

Sub test()

 With Columns("B")
  .Replace "Jay", "Jason", xlWhole
  .Replace "Steve", "Steven", xlWhole
  .Replace "Rog", "Roger", xlWhole
 End With

End Sub

使用Select Case(对于“A”列):

 Select Case Cells(aRow, 1).Value
  Case "Jay"
   Cells(aRow, 1).Value = "Jason"
  Case "Steve"
   Cells(aRow, 1).Value = "Steven"
  Case "Rog"
   Cells(aRow, 1).Value = "Roger"
 End Select