我在Excel有一系列。 与此类似:
a | b | c | d | ||||||||
a | b | c | d | e | f | ||||||
a | b | c | d | e | f | g | h | i | j | k | l |
a | b | c | d | e | f | g | h |
我怎么能像现在这样获得每行最后一栏(此处为N=2)?
c | d | ||||||||||
e | f | ||||||||||
k | l | ||||||||||
g | h |
I tried the following:
Sub keep_last_n_columns()
Dim selectedRange As Range
Dim numColumnsToKeep As Integer
Dim lastColumn As Integer
Prompt user to select a range
On Error Resume Next
Set selectedRange = Application.InputBox("Select a range:", Type:=8)
On Error GoTo 0
Check if a range is selected
If selectedRange Is Nothing Then
MsgBox "No range selected. Macro canceled.", vbExclamation
Exit Sub
End If
Prompt user to enter the number of columns to keep
On Error Resume Next
numColumnsToKeep = Application.InputBox("Enter the number of columns to keep for each row:", Type:=1)
On Error GoTo 0
Check if a valid number is entered
If numColumnsToKeep <= 0 Then
MsgBox "Invalid number of columns. Macro canceled.", vbExclamation
Exit Sub
End If
Loop through each row in the selected range
For i = 1 To selectedRange.Rows.Count
Find the last column with data in the current row
lastColumn = selectedRange.Cells(i, selectedRange.Columns.Count).End(xlToLeft).Column
Keep only the specified number of columns
If lastColumn > numColumnsToKeep Then
selectedRange.Rows(i).Resize(, lastColumn - numColumnsToKeep).Delete Shift:=xlToLeft
End If
Next i
End Sub
It is keeping the last n rows of the biggest row and deleting the rest.