【问题标题】:How to increment a Range object with a Loop如何使用循环增加 Range 对象
【发布时间】:2016-12-06 22:32:01
【问题描述】:

在这段代码中,我尝试使用 .OffSet(1, 0).Activate 增加两个 Range 对象。

  Function Foundry_check_func(target_cell As Range, result_cell As Range)
    For x = 1 To 20
        If result_cell <= 5 Then
            target_cell = "Value 1"
        ElseIf result_cell >= 10 Then
            target_cell = "Value 2"
        Else: target_cell = "Value 3"
        End If

        With target_cell
        .Interior.Color = RGB(0, 255, 0)
        End With

        target_cell.Offset(3, 0).Activate
        result_cell.Offset(4, 0).Activate
        Debug.Print ("Value: " & result_cell & " Loop: " & x)
    Next x


    ' Don't forget to format target cell at end of loop

End Function


Sub Foundry_check()
    Main = Foundry_check_func(Range("J22"), Range("K22"))
End Sub

但是,我可以看到使用 Debug.Print 在每个循环之后,正在读取的单元格不会改变。这是输出:

Value: 1 Loop: 1
Value: 1 Loop: 2
Value: 1 Loop: 3
Value: 1 Loop: 4
Value: 1 Loop: 5
etc.

我已经使用 ActiveCell 而不是 Range 进行了类似的宏工作。但在这个程序中,我需要偏移两组单元格。一个读取数据(result_cell),另一个基于该数据写入一个值(target_cell)。我不确定如何使用 ActiveCell 来抵消同一循环中的两个不同的单元格。

任何帮助将不胜感激。

【问题讨论】:

  • 您不需要Offset Activate。直接使用Cells 集合即可。这究竟应该做什么?循环运行时间越长,Offsets 的 3 和 4 将增加 2 个范围之间的差距。
  • 尝试:set targetcell = targetcell.offset(3,0)set resultcell = resultcell.offset(4,0),而不是尝试激活单元格。您当前的代码确实激活了单元格,但仅此而已。目标和结果单元格不会改变
  • 要使for 循环成功,您需要使用迭代器 (x) 来实际更新某些内容,或者在循环中逐步更改和更新某些内容。两者都不存在。
  • @NickSlash 做到了。非常感谢

标签: vba excel


【解决方案1】:

这是我看到的问题...

你的价值没有改变,因为你的 target_cell 没有改变......你应该添加

  target_cell.address 

到你的调试脚本,你会看到它没有改变...... 要更改目标单元格,您需要设置目标单元格,您不能只激活另一个单元格...所以您可以这样做:

    set target_cell = target_cell.Offset(3, 0)
    set result_cell = result_cell.Offset(4, 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多