vba Excel宏来移动列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19688864/
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
Excel macro to move column
提问by DarylF
Basically I'm looking to move a column for one position to another.
基本上,我希望将一个位置的列移动到另一个位置。
561 DISK_GROUP_003 0 545 1
561 Disk_Group_iS 95 84144 80210
561 DISK_GROUP_iS 99 26335 26304
1415 t1_200ea 93 8804 8203
1415 t2_30010k 35 59846 21121
1415 t3_1tb72k 19 184941 36590
1415 t3_3tb72k 86 258635 224328
5018 t1_200ea 98 9905 9802
5018 t2_30015k 89 39987 35986
5018 t2_60015k 67 59984 40700
5018 t3_1tb72k 89 87567 78807
5018 t3_2tb72k 84 94412 79620
I need to move the 3rd column to the end at the right.
我需要将第 3 列移到右侧的末尾。
This is what I have tried so far:
这是我迄今为止尝试过的:
Sub moveColumn()
With ActiveSheet
Excel.Columns(3).Cut
Excel.Columns(6).PasteSpecial
End With
End Sub
But this method doesn't work as it gets a runtime error '1004'.
但是此方法不起作用,因为它会收到运行时错误“1004”。
Any help would be much appreciated.
任何帮助将非常感激。
回答by FarmerGedden
For those wondering, it's possible to do this without replacing the contents of the destination column.
对于那些想知道的人,可以在不替换目标列的内容的情况下执行此操作。
For example, to cut column B and insert it to the left of column F, you can use
例如,要剪切 B 列并将其插入到 F 列的左侧,您可以使用
Columns("B").Cut
Columns("F").Insert Shift:=xlToRight
You can also replace the named column headers with column indices, to taste (so Columns("B")
becomes Columns(2)
)
您还可以用列索引替换命名的列标题,以品尝(因此Columns("B")
变成Columns(2)
)
回答by Tim Williams
Pastespecial doesn't work with Cut. You can do this:
Pastespecial 不适用于 Cut。你可以这样做:
Columns(3).Cut Range("F1")
Columns(3).Delete Shift:=xlToLeft 'if you want to delete the empty column
回答by ErikE
The problem with the other answers given is that the cut/paste technique uses the clipboard—overwriting whatever is in it, and making it impossible for the program to operate correctly if another program that also uses the clipboard is running (such as another instance of the same VBA project).
给出的其他答案的问题在于剪切/粘贴技术使用剪贴板——覆盖其中的任何内容,并且如果另一个程序也使用剪贴板正在运行(例如另一个实例同一个 VBA 项目)。
Instead, do this:
相反,请执行以下操作:
Application.CutCopyMode = False ' don't want an existing operation to interfere
Columns("F").Insert XlDirection.xlToRight
Columns("F").Value = Columns("B").Value ' this would be one greater if to the right of F
Columns("B").Delete
Just note that if there are references to the existing column, they will break and not be updated.
请注意,如果存在对现有列的引用,它们将中断且不会更新。