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

uurv41yg  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(470)

删除内容后,我需要将单元格向右移动。Excel没有提供此选项,我只有4个选择:- 单元格左移-单元格上移-整行-整列
最后,我希望在我的VBA代码中得到类似这样的结果:

Selection.Delete Shift:=xlToRight

我从

Selection.Delete Shift:=xlToLeft

谢谢你在这方面的任何帮助提前帕特里克
我最终得到了这个,它的工作amzingly罚款:

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

我需要使用在顶层定义的变量,因为我需要向右移动的范围永远不会有相同的列数。
我希望这对将来的其他人也有帮助。感谢所有人的回复

bttbmeg0

bttbmeg01#

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

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
iecba09b

iecba09b2#

我同意这个问题不应该太复杂的评论,但是我认为这个问题值得回答,它保留了移动单元格(区域左边的单元格)的格式,但是清除了删除单元格的格式和内容。

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

相关问题