如何将相同的IF语句应用于同一列中的多个单元格? (EXCEL)

我目前正在研究一个macros,为工作创build一个不同产品和选项代码的matrix。 我需要的大部分信息已经从我们运行的订单创build系统中导出。 然而,其中一个不导出的东西是对大约150个选项代码的描述。 每个选项代码都带有一个在单独工作表中概述的描述,所以不必总是引用其他工作表,而是决定使用IF语句将描述编程到代码中。 我的目标是编写一个程序,查看列中的每个选项代码,然后在相邻列中插入该选项代码的匹配描述。

例如:我的程序会说:如果活动单元格显示“AAAAA”,然后select一个单元水平偏移的单元格并插入“选项1”。 否则,如果它显示“BBBBB”,则插入另一个选项说明。

由于我们的产品订单总是在变化,我需要每周提供大约3000个产品的信息,所以我需要知道如何input一次我的条件,然后插入一段代码,告诉程序执行下一步(X)列中的选项数量,或者只要单元格中包含数据。

我很确定一个循环会解决我的问题,但我还没有find一个满足我的要求的循环脚本。

以下是我到目前为止:

Private Sub Option_Matrix_2() 'Enters data for Option code Description into worksheet Range("G4").Select If ActiveCell.FormulaR1C1 = "AAAA" Then ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Activate ActiveCell.FormulaR1C1 = "Description 1" ElseIf ActiveCell.FormulaR1C1 = "CCCCC" Then ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Activate ActiveCell.FormulaR1C1 = "Description 2" ElseIf ActiveCell.FormulaR1C1 = "EEEEE" Then ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Activate ActiveCell.FormulaR1C1 = "Description 3" Else ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Activate ActiveCell.FormulaR1C1 = "" End If 

由于我有超过3000个产品和150个不同的选项,我需要知道我需要插入什么来告诉macros运行包含数据的列中的每个单元的代码。 在这种情况下,它将是(“G4:G3000”)

如果还有其他需要的信息,请告诉我,我会很乐意以任何方式提供帮助

我会做什么@Jeepedbuild议在评论中,但如果你真的想在vba中做到这一点:

 Private Sub Option_Matrix_2() Dim cl As Range Dim ws As Worksheet Set ws = Sheets("Sheet1") ' change to your sheet 'Enters data for Option code Description into worksheet For Each cl In ws.Range("G4:G3000") If cl.FormulaR1C1 = "AAAA" Then cl.Offset(, 1).FormulaR1C1 = "Description 1" ElseIf cl.FormulaR1C1 = "CCCCC" Then cl.Offset(, 1).FormulaR1C1 = "Description 2" ElseIf cl.FormulaR1C1 = "EEEEE" Then cl.Offset(, 1).FormulaR1C1 = "Description 3" Else cl.Offset(, 1).FormulaR1C1 = "" End If Next cl End Sub 

或者更好的使用Select Case:

 Private Sub Option_Matrix_2() Dim cl As Range Dim ws As Worksheet Set ws = Sheets("Sheet1") ' change to your sheet 'Enters data for Option code Description into worksheet For Each cl In ws.Range("G4:G3000") Select Case cl Case "AAAA": cl.Offset(, 1) = "Description 1" Case "CCCC": cl.Offset(, 1) = "Description 2" Case "EEEE": cl.Offset(, 1) = "Description 3" Case Else: cl.Offset(, 1) = "" End Select Next cl End Sub 

你可以试试这个

 Option Explicit Private Sub Option_Matrix_3() With Sheets("Sheet01").Range("G4:G3000") ' change to your actual sheet name and range .Copy With .Offset(, 1) .PasteSpecial xlPasteValues .Replace What:="AAAA", LookAt:=xlWhole, Replacement:="Description 1", SearchOrder:=xlByColumns, MatchCase:=True .Replace What:="CCCCC", LookAt:=xlWhole, Replacement:="Description 2", SearchOrder:=xlByColumns, MatchCase:=True .Replace What:="EEEEE", LookAt:=xlWhole, Replacement:="Description 3", SearchOrder:=xlByColumns, MatchCase:=True End With End With End Sub 

似乎相当快!