vba界面操作技巧
- 运行子过程 F5
- 右键插入模块
- 工具栏 视图 标准
界面
Range操作单元格对象
【1】a1赋值1
Sub fz()
Range("a1") = 1
' a1赋值为1,写在模块里
End Sub
【2】a1-a100赋值为1
Sub fz2()
Dim i As Integer
For i = 1 To 100
Range("a" & i) = 1
Next
End Sub
【3】ai=i赋值
Sub fz3()
Dim i As Integer
For i = 1 To 100
Range("a" & i) = i
Next
End Sub
【4】每隔7个改颜色(避免相对引用)
Sub gys()
Dim i As Integer
For i = 1 To 100 Step 7
'录制宏形成的。绝对引用,选中单元格修改颜色
Range("A" & i).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Next
End Sub
改颜色
IF函数
例题
- 如果B列为理工,C列对应LG;文科对应WK;财经对应CJ
- E列为男,F列对应为先生;E列为女,F列对应为女士
- D列如果有空白,删除整行(从上往下删数据时会跳行,当有连续两列为空白时,第二列会逃过一劫,所以得从下往上删除)
例题
Sub pd()
Dim i As Integer
For i = 26 To 2 Step -1
'处理专业代号
If Range("b" & i) = "理工" Then
Range("c" & i) = "LG"
ElseIf Range("b" & i) = "文科" Then
Range("c" & i) = "WK"
Else
Range("c" & i) = "CJ"
End If
'处理称呼
If Range("e" & i) = "男" Then
Range("f" & i) = "先生"
Else
Range("f" & i) = "女士"
End If
'处理空白数据
If Range("d" & i) = "" Then
'删除空格录制而成。点击空白单元格,删除整行
Range("D" & i).Select
Selection.EntireRow.Delete
End If
Next
End Sub
结果
退出循环
- 工资条
Sub gzttz()
Dim i As Integer
'一共11条,表头也有11条,总共22条,倒数第1条表头21,所以i从3到21
For i = 3 To 2000 Step 2
'if 函数控制for循环
If Range("a" & i) = "" Then
Exit For
End If
'选择第一行,回到第i列,选择第一个单元格,插入复制单元格
Rows("1:1").Select
Application.CutCopyMode = False
Selection.Copy
Range("A" & i).Select
Selection.Insert Shift:=xlDown
Next
End Sub
Sub sc()
For i = 3 To 2000
If Range("a" & i) = "" Then
Exit For
End If
Range("a" & i).Select
Application.CutCopyMode = False
Selection.EntireRow.Delete
Next
End Sub