VBA学习

VBA学习

一、打开Execl的编程界面

1、点击文件=》选项=》自定义功能区=》选择开发者工具;

2、点击出现的开发者工具,里面就有可提供书写VBA的工具;

二、第一个VBA程序

点击插入,新建按钮,在按钮宏中书写以下代码

Sub 按钮1_Click()
    MsgBox ("Hello VBA")
End Sub

三、判断语句

Sub 按钮1_Click()
'声明一个字符串变量'
Dim opt As String
'获取单元格的值'
opt = Cells(25, 4)
'if语句判断'
If opt = "+" Then
Cells(25, 7) = Cells(25, 3) + Cells(25, 5)
End If

If opt = "-" Then
Cells(24, 6) = Cells(24, 2) - Cells(24, 4)
End If

If opt = "*" Then
Cells(24, 6) = Cells(24, 2) * Cells(24, 4)
End If

If opt = "/" Then
Cells(24, 6) = Cells(24, 2) / Cells(24, 4)
End If

End Sub

讲解

'声明一个字符串 用来表示运算符 注释使用 '
Dim operator As String

单引号用来表示注释(是英文状态下的单引号 English English English)
Dim 用来申明变量
operator就是变量名
As 就是"是"
String 字符串类型
放在一起就是:声明了一个字符串类型的变量,这个变量叫做operator

变量类型包含以下几种(只是入门教程 我不写全 只写容易记的)
字符串型 String 就是咱们整天表示汉字 英文的那个类型
整数型 Integer 就是咱们表示 1 2 3 整数的那个类型 所以如果咱们想声明一个age来表示一个人的年龄就可以这样 Dim age As Integer
日期型 Date
货币型 Currency

四、根据多行锁定一行

获取其他Sheet的单元格的值

MsgBox (Sheets(“项目操作数统计”).Cells(2, 1))

Sub 筛选()

  Dim a As Integer
  
   a = Range("A65536").End(3).Row
   
   For i = 3 To a Step 1
   
   If Cells(i, 1) = Cells(3, 9) And Cells(i, 2) = Cells(4, 9) And Cells(i, 4) = Cells(5, 9) And Cells(i, 5) = Cells(6, 9) Then
   
   Cells(10, 9) = Cells(i, 6)
   Cells(11, 9) = Cells(i, 7)
   
   End If
     
   Next

End Sub

2、数据清洗

Sub 按钮16_Click()

Dim val As String

Select Case Cells(4, 7)

Case "S316_6子电路"

val = "316-6子电路"

Case "S316_6功放1"

val = "316-6功放1"

Case "S316_6功放2"

val = "316-6功放2"

Case "S316_6功放3"

val = "316-6功放3"

Case "S316_6"

val = "316-6"

Case "S316_5_SC_子电路"

val = "316-5(SC)子电路"

Case "S316_5_SC"

val = "316-5(SC)"

Case "S316_5模块总装"

val = "316-5模块总装"

Case "S316_5_x_子电路"

val = "316-5(x)子电路"

Case "S316_5_x"

val = "316-5(x)"

Case "HX-PAGR81BXF02子电路"

val = "HX-PAGR81BXF02子电路"

Case "HX_PAGR81BXF02"

val = "HX-PAGR81BXF02"

Case Else

MsgBox ("选择了其他")

End Select
   
MsgBox (val)
   
End Sub

3、完整代码

Sub 按钮16_Click()

Dim val As String

Select Case Cells(4, 7)

Case "S316_6子电路"

val = "316-6子电路"

Case "S316_6功放1"

val = "316-6功放1"

Case "S316_6功放2"

val = "316-6功放2"

Case "S316_6功放3"

val = "316-6功放3"

Case "S316_6"

val = "316-6"

Case "S316_5_SC_子电路"

val = "316-5(SC)子电路"

Case "S316_5_SC"

val = "316-5(SC)"

Case "S316_5模块总装"

val = "316-5模块总装"

Case "S316_5_x_子电路"

val = "316-5(x)子电路"

Case "S316_5_x"

val = "316-5(x)"

Case "HX-PAGR81BXF02子电路"

val = "HX-PAGR81BXF02子电路"

Case "HX_PAGR81BXF02"

val = "HX-PAGR81BXF02"

Case Else

MsgBox ("选择了其他")

End Select
   
Dim a As Integer
  
a = Sheets("项目操作数统计").Range("A65536").End(3).Row
   
 For i = 3 To a Step 1
   
   If Sheets("项目操作数统计").Cells(i, 1) = val And Sheets("项目操作数统计").Cells(i, 2) = Cells(4, 8) And Sheets("项目操作数统计").Cells(i, 4) = Cells(4, 9) And Sheets("项目操作数统计").Cells(i, 5) = Cells(4, 10) Then

   Cells(4, 13) = Sheets("项目操作数统计").Cells(i, 6)
   
   Cells(4, 14) = Sheets("项目操作数统计").Cells(i, 7)
   
   End If
     
   Next

   
End Sub

后续遇到问题继续更新

你可能感兴趣的:(VBA)