VBA 向上/向下移动选定范围(带偏移?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41408969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA move selected range up / down (with offset?)
提问by AugustinB
I am building a tool where user-selected cell contents is moved around with arrow shapes.
我正在构建一个工具,其中用户选择的单元格内容以箭头形状移动。
The code below works great to move 1 or more group of adjacent cells down. However, reversing the code seems tricky (+1 in offset does not work :-?)
下面的代码非常适合将一组或多组相邻单元格向下移动。但是,反转代码似乎很棘手(偏移量中的 +1 不起作用 :-?)
Any idea? Thank you, Augustin
任何的想法?谢谢你,奥古斯丁
Sub Move_Up()
Selection.Cut
Selection.Offset(-1, 0).Select
Selection.Insert Shift:=xlDown
End Sub
回答by Gary's Student
If you want to move a Selected
block of cells upby one row then:
如果要将一Selected
组单元格向上移动一行,则:
Sub ShiftBlockUp()
Dim r As Range
Set r = Selection
Intersect(r(1).EntireRow, r).Offset(-1, 0).Delete Shift:=xlUp
End Sub
If you want to move a Selected
block of cells downby one row then:
如果要将一Selected
组单元格向下移动一行,则:
Sub ShiftBlockDown()
Dim r As Range
Set r = Selection
Intersect(r(1).EntireRow, r).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
回答by user3598756
supposing cells are to be moved around and overwritten ones are just shifted where moved ones once were, the code could be the following:
假设单元格要四处移动,而被覆盖的单元格只是移动到曾经移动过的位置,代码可能如下:
Sub MoveUp()
Selection.Rows(Selection.Rows.count + 1).Insert Shift:=xlDown
Selection.Rows(1).Offset(-1).Cut Selection.Rows(Selection.Rows.count + 1)
Selection.Rows(1).Offset(-1).Delete Shift:=xlUp
Selection.Offset(-1).Select
End Sub
Sub MoveDown()
Selection.Rows(1).Insert Shift:=xlDown
Selection.Rows(Selection.Rows.count).Offset(2).Cut Selection.Rows(1)
Selection.Rows(Selection.Rows.count).Offset(2).Delete Shift:=xlUp
Selection.Offset(1).Select
End Sub