Excel VBA:基于单元格值的If语句(2个实用例子)

  • Share This
Hugh West

在这篇文章中,我将告诉你如何使用一个 如果声明 VBA 在Excel中基于一个单元格的值。

Excel VBA:基于单元格值的If语句(快速浏览)

 Sub If_Statement_Based_On_a_Single_Cell() If Range("C3").Value>= 40 Then Range("D3").Value = " Passed" Else Range("D3").Value = "Failed" End If End Sub 

下载实践工作手册

下载这本练习手册,在阅读本文时进行练习。

基于单元格值的if语句.xlsm

Excel VBA中基于单元格值的if语句

这里我们有一个工作表,其中包含了 名称和标记 某个学校的一些学生在考试中的表现。

我们的目标是学习如何使用 如果声明 在Excel中 VBA 基于该数据集的一个单元格值。

1.Excel VBA中基于单个单元格值的If语句

首先,我们将学习如何使用基于单个单元格值的If语句。

例如,让我们尝试看看Natalia Austin是否通过了考试,也就是说,单元格中的标记是否是 C3 大于 40 或不。

栏目 D 就是说,如果单元格 C3 包含一个大于40的分数,单元格 D3 将包含 "通过" 否则,它将包含 "失败了" .

我们将使用一个 VBA 范围 对象来创建这个 如果声明 基于单元格的值。

ǞǞǞ VBA 这方面的代码将是。

⧭ VBA代码。

 Sub If_Statement_Based_On_a_Single_Cell() If Range("C3").Value>= 40 Then Range("D3").Value = " Passed" Else Range("D3").Value = "Failed" End If End Sub 

⧭ 输出。

运行代码,从 运行子程序/用户表格 的工具。 VBA 工具栏。

这将使细胞 D3 含有 "失败了" ,作为单元格中的标记 C3 小于 40 ( 32 ).

2.Excel VBA中基于单元格范围值的if语句

你也可以使用 如果声明 中的一系列单元格的值为基础。 VBA 你可以使用一个 循环 为了这个目的。

例如,在这里我们可以用一个代码找出所有学生的结果。 我们将遍历一个 循环 这将检查范围内的所有单元格 C3:C12 并返回一个相应的结果。 "通过" "失败了" .

ǞǞǞ VBA 这方面的代码将是。

⧭ VBA代码。

 Sub If_Statement_Based_On_a_Range_of_Cells() For i = 1 To Range("C3:C12").Rows.Count If Range("C3:C12").Cells(i, 1).Value>= 40 Then Range("D3:D12").Cells(i, 1).Value = " Passed" Else Range("D3:D12").Cells(i, 1).Value = "Failed" End If Next i End Sub 

⧭ 输出。

运行代码,从 运行子程序/用户表格 的工具。 VBA 工具栏,它将返回 "通过" 为大于的分数 40 而 "不合格 "则是指那些不达标的。 n 40 .

需要记住的事情

这里我展示了一个 如果声明 但如果你愿意,你可以在一个条件中使用多个条件。 如果声明 .

如果你使用 键入多个条件,用一个 .

而如果你使用 键入多个条件,用一个 .

例如,要检查单元格中的标记是否为 B3 大于 40 和小于 50 或不,使用。

 如果(Range("C3").Value> 40 或者Range("C3").Value <50)那么 

Hugh West is a highly experienced Excel trainer and analyst with over 10 years of experience in the industry. He holds a Bachelor's degree in Accounting and Finance and a Master's degree in Business Administration. Hugh has a passion for teaching and has developed a unique teaching approach that is easy to follow and understand. His expert knowledge of Excel has helped thousands of students and professionals worldwide improve their skills and excel in their careers. Through his blog, Hugh shares his knowledge with the world, offering free Excel tutorials and online training to help individuals and businesses reach their full potential.