简体   繁体   English

切换单元宏-奇怪的行为

[英]Switch Cells Macro - Strange behaviour

I have created a macro for the purpose of switching the contents between two cells. 我创建了一个宏,目的是在两个单元格之间切换内容。 Although it works, I think it could be written in some more elegant way. 尽管它可以工作,但我认为可以用更优雅的方式编写它。

Consider the folowing example: 考虑以下示例:

在此处输入图片说明

Supose that in the previous picture you select the first two cells ("Jack" and "The"). 假设您在上一张图片中选择了前两个单元格(“ Jack”和“ The”)。 After you run the macro, the contents of the selected cells are switched. 运行宏后,将切换选定单元格的内容。

The working code is this: 工作代码是这样的:

Sub SwitchCells()

    Dim R As Range
    Set R = Range(Selection.Address)

    Dim Temp As String

    If R.Count = 2 Then
        Temp = R(1).Value
        R(1) = R(2)
        R(2) = Temp
    End If

End Sub

Although is works, I would like that the temporary variable would be also an Range Object (and not a String like in the previous example), so that the macro would just switch places between objects. 尽管可行,但我希望该临时变量也可以是Range对象(而不是上一个示例中的String),以便宏可以在对象之间切换位置。 I would like to do something like this 我想做这样的事情

Sub SwitchCells()

    Dim R As Range
    Set R = Range(Selection.Address)

    Dim Temp As Range

    If R.Count = 2 Then
        Set Temp = R(1)
        R(1) = R(2)
        R(2) = Temp
    End If

End Sub

The problem in this second version of the macro is that when R(1) gets the value of R(2) , so does the temporary variable Temp 宏的第二个版本中的问题是,当R(1)获得R(2)的值时,临时变量Temp

It seems that Temp is not a variable but a pointer to the address of the variable. 似乎Temp不是变量,而是指向变量地址的指针。

I don't quite understand exaclty why is this happening. 我不太明白为什么会这样。 Can you please explain or point out some direction for the reason of this behaviour? 您能否出于这种行为的原因进行解释或指出一些方向?

Thank you for your time. 感谢您的时间。

Eduardo. 爱德华多

Range is an object type. 范围是一种对象类型。 A variable like Temp in the 2nd version of your macro will hold a reference to the object you have set it to - R(1) in this case. 在此宏的第二版中,像Temp这样的变量将保存对您已将其设置为R(1)的对象的引用。 It does not create a new copy of that object so any changes to R(1) will be reflected in Temp . 它不会创建该对象的新副本,因此对R(1)任何更改都将反映在Temp

The normal way to work around this would be to create a new object and copy the relevant values over to it. 解决此问题的通常方法是创建一个新对象并将相关值复制到该对象上。 Unfortunately Range objects cannot be directly created and only exist as part of a Worksheet object: 不幸的是,范围对象不能直接创建,只能作为工作表对象的一部分存在:

Dim r As Range
' This line won't compile because we can't create a new Range
Set r = New Range
' This line will trigger a runtime error
Set r = CreateObject("Excel.Range")

For the specific case of two cells which are in the same column and adjacent to each other, there is a straightforward workaround: 对于在同一列中且彼此相邻的两个单元格的特定情况,有一个简单的解决方法:

R(2).Cut
R(1).Insert Shift:=xlDown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM