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

shift cells right when deleting a cell in vba

我需要在删除内容后向右移动单元格。 excel没有给出这个选项,我只有4个选择: - 向左移动单元格 - 向上移动单元格 - 整行 - 整列

最后,我希望在我的 VBA 代码中得到这样的结果:

Selection.Delete Shift:=xlToRight

我从

Selection.Delete Shift:=xlToLeft

提前感谢您对此的任何帮助 桥 帕特里克

我终于解决了这个问题,而且效果非常好:

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

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

我希望这对将来的其他人也有帮助。 感谢大家的回复

我同意它不应该非常复杂的评论,但我认为它值得一个答案。这会保留已移动单元格(范围左侧的单元格)的所有格式,但会清除已删除单元格的格式和内容。

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

我更喜欢这种简单的方法:

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