excel学习库

excel表格_excel函数公式大全_execl从入门到精通

Excel VBA初学者示例

在提高工作效率或节省工作时间方面,宏是你最好的朋友。从小任务到大任务,我们都可以使用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

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年12月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
      友情链接