Excel vba移动列并保留宽度

时间:2011-03-08 16:59:37

标签: excel excel-vba vba

我有基于按键左右移动列的代码,但在移动列时不会保留列宽。我想要移动的柱子保持其宽度,并且移动的柱子也保持它们的宽度。

Public Sub moveColumnleft()

    ActiveCell.EntireColumn.Select
    Selection.EntireColumn.Cut
    If ActiveCell.Column = 1 Then Exit Sub

    ActiveCell.offset(0, -1).Insert Shift:=xlLeft
    ActiveCell.offset(0, -1).Select


End Sub

Public Sub moveColumnRight()

    ActiveCell.EntireColumn.Select
    Selection.EntireColumn.Cut
    ActiveCell.offset(0, 2).Insert Shift:=xlRight
    ActiveCell.offset(0, 1).Select

End Sub

1 个答案:

答案 0 :(得分:2)

存储移动列宽对我有用(Excel 2007)。见下面的代码

Public Sub moveColumnleft()
    ActiveCell.EntireColumn.Select
    Selection.EntireColumn.Cut
    '' store column width in variable **tmp**
    Dim tmp As Double 
    tmp = ActiveCell.EntireColumn.ColumnWidth
    If ActiveCell.Column = 1 Then Exit Sub

    ActiveCell.Offset(0, -1).Insert Shift:=xlLeft
    ActiveCell.Offset(0, -1).Select
    '' apply the stored width to the moved column
    Range(ActiveCell.Address).ColumnWidth = tmp
End Sub