在Worksheet_change过程中,范围变量发生了变化,我不知道如何处理。

问题描述 投票:0回答:1

我遇到了一个奇怪的问题,幸运的是,我几乎还没有任何其他的代码,所以我可以把它缩小到它的来源。 我的问题比我的描述更容易从代码中读出来,但我还是要试试:-我试图记住一个在我的工作簿中被剪切的范围,以便以后可以 "Undo"-我发现了一个伟大的函数,它告诉我被剪切的单元格的范围(返回为 "GetCopiedRange",函数名称也是一样的)-函数工作并返回正确的值,但后来在Worksheet_Change中,范围突然不同了,没有任何东西给它一个新的值。

TL;DR:下面代码中的CutRange.Address怎么会在我选择一个范围的时候和之后改变一个范围内的值的时候不一样?

Dim CutRange As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Application.CutCopyMode = xlCut Then
    Call GetCopiedRange 'This function changes value of variable "GetCopiedRange" (Range) to the range that is cut to clipboard
    Set CutRange = GetCopiedRange 'Save the range under a new variable because if I refer straight to GetCopiedRange later, it doesn't work
    MsgBox ("Cut range: " & CutRange.Address)
End If
'This sub works perfectly. If a range is cut to clipboard, Msgbox tells the range correctly
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

If Not CutRange Is Nothing Then
    MsgBox CutRange.Address
End If
'This sub works incorrectly(!?) CutRange.address is somehow now the destination of paste instead of where it was cut. How did it change in between?
'Even though when cut-paste operation is carried out, change occurs twice: first to the cut range and then the paste range. Even during the first one, CutRange.Address is somehow already changed to the paste range address
End Sub

EDIT:我不明白所说的Function的内容怎么会影响这个结果,我希望我们不必去做,因为这是一个复制的函数,比我能理解的复杂得多。但是,当我试图把CutRange从这一切中去掉,直接引用Worksheet_Change中的GetCopiedRange时,我得到了一个错误 "无法从剪贴板获取数据",这是函数里面的错误信息。然而由于我使用的是CutRange-variable,我看不出那个怎么会改变

worksheet-function
1个回答
0
投票

我想我已经找到了我自己问题的答案,并暴露了我自己是个新手或白痴。

修正:当我用一个字符串而不是一个范围来跟踪切割范围时,值会保持原样。如果我错了,请纠正我,但似乎当你SET一个range来匹配另一个range时,第一个range会随着后者自动改变。

下一个问题。有没有办法将一个范围保存为一个范围,而不改变它的值,除非我这么说?

© www.soinside.com 2019 - 2024. All rights reserved.