|
如果要在Excel中插入較多的行或列,例如要插入上百行,用普通的操作方法有些繁瑣,我們可以用VBA代碼來輕松實(shí)現(xiàn)這一目的。在VBA編輯器的代碼窗口中輸入下列代碼,運(yùn)行前先在表格中選擇要插入行或列的位置,然后運(yùn)行代碼,在提示窗口中輸入要插入的行數(shù)或列數(shù)即可。
插入多行:
Sub InsertMultipleRows()
' 在當(dāng)前選擇的單元格或行之上插入多行
Dim
NewRows
As Long
Dim
CurrentRow
As Long
' 檢查當(dāng)前選擇的是否為行或單元格
If UCase(TypeName(Selection))
<> "RANGE" Then
MsgBox "請(qǐng)選擇行或單元格,以便在其上方插入行。", _
vbInformation
Exit Sub
End If
' 讓用戶輸入要插入的行數(shù)
NewRows =
Application.InputBox("請(qǐng)輸入要插入的行數(shù)", _
"插入多行", 1, , , , , 1)
' 如果行數(shù)為0或取消
If NewRows <= 0 Then
Exit Sub
' 插入相應(yīng)數(shù)量的行
Rows(Selection.Cells(1).Row
& ":" & _
Selection.Cells(1).Row + NewRows - 1).Insert
Shift:=xlShiftDown
End Sub
插入多列:
Sub InsertMultipleColumns()
' 在當(dāng)前選擇的單元格或列的左方插入多列
Dim
NewColumns
As Long
Dim
CurrentRow
As Long
' 檢查當(dāng)前選擇的是否為列或單元格
If UCase(TypeName(Selection))
<> "RANGE" Then
MsgBox "請(qǐng)選擇行或單元格,以便在其上方插入行。", _
vbInformation
Exit Sub
End If
' 讓用戶輸入要插入的列數(shù)
NewColumns =
Application.InputBox("請(qǐng)輸入要插入的列數(shù)", _
"插入多列", 1, , , , , 1)
' 如果列數(shù)為0或取消
If NewColumns <= 0
Then Exit Sub
' 插入相應(yīng)數(shù)量的列
For i = 1 To NewColumns
Columns(Selection.Cells(1).Column).Insert
Shift:=xlShiftToRight
Next
End Sub
|