【发布时间】: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 做到了。非常感谢