VBA宏,如果单元格包含特定值,则将特定文本返回到特定范围

时间:2020-02-14 15:53:27

标签: excel vba

我有一个Excel文件,该文件跟踪销售和生产部门的引擎状态。工作簿中的A至M列包含视为发动机状态所必需的数据。 N-AR列用于按照以下列顺序跟踪引擎状态:销售,生产,第1天,状态。一直重复到第8天(即销售,生产,第8天,状态)。

Sample file

第AV列称为“ MB51已发货”,而AY列称为“标题转移”。

我想创建一个宏,以便:

1)如果在AV列中为Shippep,则销售和生产列中的剩余天数将为Rollup

See print screen here

Ex:在所附的打印屏幕中(此列可能与示例文件略有不同,但概念相同),请注意,数据输入到第6天(AH-AK列),并且用户输入了{{进入第6天的状态后,在AV列中输入1}}。在这里,我希望宏在第6天之后为每个空白的Sales and Production单元格返回Shipped,如屏幕截图中黑色突出显示。

另一个示例,如果输入第2天的状态(列R-U)后,用户输入Rollup,则此后的每个Sales and Production单元格都将返回Shipped

2)如果最后输入的销售单元格显示Rollup,则在AY列(第51列)中返回Title Transfer

See print screen here

因此,在我的打印屏幕中,最后输入状态为x的Sales单元为第4天的Z列,然后宏应在AY列中返回Title Transfer,如屏幕截图所示。

我没有任何编程知识,因此非常感谢您的帮助!谢谢!!!

1 个答案:

答案 0 :(得分:0)

草稿很粗,但是您可以将此代码添加到Worksheet_Change(ByVal Target As Range)事件中

赞:

Code position

代码:

Dim lastColumn As Long
Dim counter As Long

Application.EnableEvents = False

' Check if header is "MB51 Shipped"
If Me.Cells(1, Target.Column).Value = "MB51 Shipped" Then

    ' Get last column based on first row
    lastColumn = Me.Cells(1, Me.Columns.Count).End(xlToLeft).Column

    ' Check all cells in row and find matches for Sales and Production
    For counter = 1 To lastColumn

        ' Check if header match and cell is not empty
        If (Me.Cells(1, counter).Value = "Sales" or Me.Cells(1, counter).Value = "Production") And Me.Cells(Target.Row, counter).Value = vbNullString Then

            Me.Cells(Target.Row, counter).Value = "RollUp"

        End If

    Next counter

End If

Application.EnableEvents = True

让我知道它是否有效