Excel中elseif函数使用流程的具体操作
相关话题
excel使用elseif流程简写if函数嵌套条件的方法,如何进行具体操作的呢?今天,小编就教大家在Excel中elseif函数使用流程的具体操作。
Excel中elseif函数使用流程的具体步骤如下:
首先我们打开一个工作样表作为例子。

打开vba编辑窗口,使用alt+f11快捷组合键或在开发者工具标签中点击vb快捷按钮,进入。

我们设计一个代码,比如满足岗位工资100的为红色,岗位工资300的为蓝色,岗位工资900的为绿色。这样我们写下如下代码。
Sub 颜色()
For i = 6 To 13
t = Sheets(1).Cells(i, 7).Value '取得数据
If t = 100 Then
Sheets(1).Cells(i, 7).Select
Selection.Font.ColorIndex = 3
End If
If t = 300 Then
Sheets(1).Cells(i, 7).Select
Selection.Font.ColorIndex = 5
End If
If t = 900 Then
Sheets(1).Cells(i, 7).Select
Selection.Font.ColorIndex = 4
End If
Next
End Sub

上面的代码其实是在循环运行并每次都对值做了3次判断,虽然计算机运行速度快,大家感觉不到差异,但是我们可以对其进行修改。来达到优化代码的目的。

这里需要使用到elseif函数。简写代码如下:
Sub 颜色()
For i = 6 To 13
t = Sheets(1).Cells(i, 7).Value '取得数据
If t = 100 Then
c = 3
ElseIf t = 300 Then
c = 5
ElseIf t = 900 Then
c = 4
Else: c = 0
End If
Sheets(1).Cells(i, 7).Select
Selection.Font.ColorIndex = c
Next
End Sub

这里可以解释一下函数的运行方法,首先是循环语句for历遍sheet1表格中G列6-13行数据。并每次对其取值进行判断,最关键的是对字体颜色进行变量定义,这样可以简化代码中选择单元格和进行字体颜色变更的多次操作。
