开发者

Excel vba move columns and preserve widths

I have code to move columns left and right based on keypresses, but the column widths a开发者_如何学Pythonren't preserved as I move the columns. I'd like the column I'm moving to retain its width, and the columns its moving through also preserve their widths.

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


Storing the moved column witdth worked for me (Excel 2007). See code below

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜