VBA操作Excel笔记

修改单元格

Application.Workbooks(1).Worksheets(1).Cells(1,1) = 100

每次修改数据后不要更新显示,可提高运行速度

1
2
Application.ScreenUpdating = False
Application.ScreenUpdating = True

打开一个新的workbook

Workbooks.Add

expression.Evaluate()

类似于python的eval

使用Worksheet Function找范围内最小值

VBA中给对象赋值时用Set,且不能省略

1
2
Set myRange = Worksheets(1).Range(“A1:C10")
answer = Application.WorksheetFunction.Min(myRange)

遍历worksheet

1
2
3
4
5
6
7
8
9
10
11
Private Sub ListSheets()
Dim sh As Worksheet
Dim rng As Range
Dim i As Integer

For Each sh In ThisWorkbook.Sheets
Set rng = sh.Range("A5")
rng.Offset(i, 0).Value = sh.Name
i = i + 1
Next sh
End Sub

在已有工作表最右侧插入新的工作表

Set sh = ThisWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))

Protect 和 Unprotect 方法

设置保护工作表,效果等同于选择“工具 - 保护 -保护工作表”

删除工作表

Worksheets("sheet1").Delete

Range对象

Range对象是具体操作的单元格对象

Cells方法

Cells用来选择单元格

1
2
3
4
5
6
7
8
9
10
11
12
Sub SetUpTable()
Dim i As Long
Dim j As Long
Worksheets(1).Activate
For i = 1 To 5
Cells(1, i + 1).Value = 1990 + i
Next i
For j = 1 To 4
Cells(j + 1, 1).Value = "Q" & j
Next j
Cells(32, 32) = 2
End Sub

Range对象也可以调用Cells方法,选择区域中相对位置的单元格。

删除指定列

Worksheets(1).Columns(3).Delete

插入一列

Worksheets(1).Columns(3).Insert

工作表的保护/解除保护

ActiveSheet.Protect "passwd"
ActiveSheet.Unprotect "passwd"

选中range中的相对位置单元格

A.Cells(9, 1)

改变range内单元格背景色

Range("F30").Interior.Color = RGB(255, 255, 255)

改变range内单元格内字体颜色

Range("F30").Font.Color

设置range内单元格的数据验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
With A.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="option1,option2,option3"
.IgnoreBlank = False
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.IMEMode = xlIMEModeNoControl
.ShowInput = True
.ShowError = True
End With