在提高工作效率或节省工作时间方面,宏是你最好的朋友。从小任务到大任务,我们都可以使用VBA编码语言实现自动化。我们知道,您可能经常会想到Excel的一些限制,但使用VBA编码,您可以消除所有这些限制。如果您在VBA方面遇到困难,并且在本文中还是初学者,我们将给出一些Excel中VBA宏代码的有用示例。
1 列出所有工作表名称
代码
Sub Print_Sheet_Names()
Dim i As Integer
For i = 1 To Sheets.Count
Cells(i, 1).Value = Sheets(i).Name
Next i
End Sub
示例

2 在VBA中插入不同的颜色索引
代码
Sub Insert_Different_Colours()
Dim i As Integer
For i = 1 To 56
Cells(i, 1).Value = i
Cells(i, 2).Interior.ColorIndex = i
Next
End Sub
示例

3 从顶部插入序列号
代码
Sub Insert_Numbers_From_Top()
Dim i As Integer
For i = 1 To 10
Cells(i, 1).Value = i
Next i
End Sub
示例

4 从底部插入序列号
代码
Sub Insert_Numbers_From_Bottom()
Dim i As Integer
For i = 20 To 1 Step -1
Cells(i, 1).Value = i
Next i
End Sub
示例

5 插入从10到1的序列号
代码
Sub Ten_To_One()
Dim i As Integer
Dim j As Integer
j = 10
For i = 1 To 10
Range("A" & i).Value = j
j = j - 1
Next i
End Sub
示例

6 根据需要插入工作表
代码
Sub AddSheets()
Dim ShtCount As Integer, i As Integer
ShtCount = Application.InputBox("你要插入的工作表数", "Add Sheets", , , , , , 1)
If ShtCount = False Then
Exit Sub
Else
For i = 1 To ShtCount
Worksheets.Add
Next i
End If
End Sub
示例

7 从工作簿中删除所有空白工作表
代码
Sub Delete_Blank_Sheets()
Dim ws As Worksheet
Application.DisplayAlerts = False
Application.ScreenUpdating = False
For Each ws In ActiveWorkbook.Worksheets
If WorksheetFunction.CountA(ws.UsedRange) = 0 Then
ws.Delete
End If
Next ws
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
8 每隔一行插入空行
代码
Sub Insert_Row_After_Every_Other_Row()
Dim rng As Range
Dim CountRow As Integer
Dim i As Integer
Set rng = Selection
CountRow = rng.EntireRow.Count
For i = 1 To CountRow
ActiveCell.EntireRow.Insert
ActiveCell.Offset(2, 0).Select
Next i
End Sub