在vba中删除单元格时右移单元格

时间:2016-12-27 14:29:54

标签: excel vba shift

删除内容后,我需要将单元格移到右侧。 excel不提供此选项,我只有4个选择: - 向左移动细胞 - 移动细胞 - 整行 - 整栏

最后,我想在我的VBA代码中找到一些东西:

Selection.Delete Shift:=xlToRight

我改变了

Selection.Delete Shift:=xlToLeft

提前感谢您对此提供任何帮助 Brgds 帕特里克

我最终得到了这个并且它的工作非常好:

Sub ShiftRight()
 Selection.End(xlToRight).Select
 numcol = ActiveCell.Column
 numcol2 = numcol
 numcol = (numcol - lngColNumber) + 5
 strcolletter = Split(Cells(1, numcol - 1).Address, "$")(1)
 strcolletter2 = Split(Cells(1, numcol2).Address, "$")(1)
 Range(Myrange).Select
 Selection.Cut Destination:=Columns(strcolletter & ":" & strcolletter2)
End Sub

我需要使用在顶层定义的变量,因为我需要向右移动的范围永远不会有相同的列数。

我希望将来也能帮助别人。 感谢所有回复

2 个答案:

答案 0 :(得分:0)

我同意这些评论不应该大规模复杂,但我认为值得回答。这样可以保留已移位单元格的任何格式(范围左侧的格式),但会清除已删除单元格的格式和内容。

Sub DelRight()

Dim firstColumn, lastColumn, firstRow, lastRow, nRows, nCols, colsToShift As Long
Dim sheet As Worksheet
Dim rangeToCopy, rangeToReplace, rangeToDelete As Range

Set sheet = ActiveSheet

firstColumn = Selection.Column
nCols = Selection.Columns.Count
nRows = Selection.Rows.Count
lastColumn = firstColumn + nCols - 1
colsToShift = firstColumn - 1
firstRow = Selection.Row
lastRow = firstRow + nRows - 1

' Shift cells to left of the range to the right hand end of the range
With sheet
    If firstColumn > 1 Then
        Set rangeToCopy = .Range(.Cells(firstRow, 1), .Cells(lastRow, colsToShift))
        Set rangeToReplace = .Range(.Cells(firstRow, lastColumn - colsToShift + 1), .Cells(lastRow, lastColumn))
        rangeToCopy.Copy destination:=rangeToReplace
    End If

    ' Delete cells to the left of the shifted cells
    Set rangeToDelete = .Range(.Cells(firstRow, 1), .Cells(lastRow, lastColumn - colsToShift))
    rangeToDelete.ClearContents
    rangeToDelete.ClearFormats
End With

End Sub

答案 1 :(得分:0)

我喜欢这个简单的方法:

Sub DELETE_MOVE_TO_RIGHT()

Dim firstcolumn As Integer
Dim lastcolumn As Integer

Dim firstrow As Integer
Dim lastrow As Long

Dim i As Integer
Dim j As Integer

Dim nrows As Long
Dim ncols As Integer

ncols = Selection.Columns.Count
nrows = Selection.Rows.Count
firstcolumn = Selection.Column
lastcolumn = firstcolumn + ncols - 1
firstrow = Selection.Row
lastrow = firstrow + nrows - 1

    Range(Cells(firstrow, firstcolumn), Cells(lastrow, lastcolumn)).SpecialCells(xlCellTypeBlanks).Delete Shift:=xlToLeft

    For j = lastcolumn To firstcolumn + 1 Step -1
        Range(Cells(firstrow, firstcolumn), Cells(lastrow, firstcolumn)).Cut
        Range(Cells(firstrow, j + 1), Cells(lastrow, j + 1)).Insert Shift:=xlToRight
    Next j

End Sub