首页 > 解决方案 > 使用 do while 循环时,我的 VBA 代码不起作用

问题描述

我下面的 VBA 代码没有循环。请帮助

Public Sub FunWithLoops()

' Create a loop using Do while loop.
'The aim is to go through a list of numbers down a row, highlight them with a different color if greater than 10.

    Dim i As Integer
    i = 1
    
    Do While i <= 10
        If ActiveCell.Value > 10 Then
        ActiveCell.Interior.Color = RGB(255, 0, 0)
        'interior changes the background color
        End If
        ActiveCell.Offset(1, 0).Select
    
    i = i + 10
    Loop
    
End Sub

标签: excelvba

解决方案


只需更正您的代码而不进行太多更改,您可能还没有准备好:

Public Sub FunWithLoops()

' Create a loop using Do while loop.
'The aim is to go through a list of numbers down a row, highlight them with a different color if greater than 10.

    Dim i As Integer
    i = 1
    
    Do While i <= 10
        If ActiveCell.Value > 10 Then ActiveCell.Interior.Color = RGB(255, 0, 0)
        ActiveCell.Offset(1, 0).Select  
       i = i + 1 ' change this to + "1" not + "10"
    Loop
    
End Sub

请注意,您ActiveCell必须始终在运行例程之前进行设置,因为例程中没有任何内容可以设置第ActiveCell一个,例如一行:

Range("A2").Select

推荐阅读