简体   繁体   English

重复宏,直到满足条件

[英]Repeat macro until the criteria is met

I am working on a macro to do a repetitive task for me. 我正在宏上为我做重复的任务。 To give you a clear view, I have prepared my initial macro (vba) code below as well as the flow chart of what it suppose to do: 为了给您一个清晰的视图,我在下面准备了我的初始宏(vba)代码以及它应做的流程图:

Here a narrative description of the macro: 这里是宏的叙述性描述:

  1. Check all the cells in Column K if it contains the word "MERGED" 检查列K中是否包含单词“ MERGED”的所有单元格
  2. IF the macro found the word "Merged", it will call another macro (Macro_X) 如果该宏找到单词“ Merged”,它将调用另一个宏(Macro_X)
  3. After calling the Macro, it will check again all the cells in Column K if it still contains the word "MERGED" 调用宏后,它将再次检查K列中的所有单元格,如果它仍然包含单词“ MERGED”
  4. If the macro still finds the word "Merged", it will call again the Macro_X. 如果宏仍然找到单词“ Merged”,它将再次调用Macro_X。
  5. The condition will only stop until the Column K doesn't contain the word "Merged". 该条件将一直停止,直到列K不包含单词“ Merged”。
  6. If the macro didn't find any "Merged" word in column K, it will now call the Macro_Z. 如果宏在K列中找不到任何“合并”字词,则它将调用Macro_Z。

     Last = Cells(Rows.Count, "K").End(xlUp).Row For i = Last To 1 Step -1 If (Cells(i, "K").Value) = "Merged" Then Call macro_x End If Next I 

在此处输入图片说明

Screen shot of column K K列的屏幕截图

在此处输入图片说明

I already have the code above but it's not working. 我已经有了上面的代码,但是无法正常工作。 Not sure why. 不知道为什么。 Could you please help to point out what's wrong or suggest a better code? 您能否帮助指出问题所在或提出更好的代码?

You can add simple Boolean variable to check if the word "MERGED" was found. 您可以添加简单的布尔变量来检查是否找到了单词“ MERGED”。

Dim Word_Found as Boolean

Last = Cells(Rows.Count, "K").End(xlUp).Row
For i = Last To 1 Step -1
    If (Cells(i, "K").Value) = "Merged" Then
        Call macro_x

        Word_Found = True
        i = LAST

    End If
Next I

If Not(Word_Found) Then Call macro_z

Above code is what can be modified from your code. 上面的代码是可以从您的代码中进行修改的代码。

Below code is written looking at your flow chart. 下面的代码是写在您的流程图。

While Not (Columns("K").Find("Merged") Is Nothing)
    Call macro_x
Wend
Call macro_z

You can call your initial macro at the end of your Macro_X. 您可以在Macro_X的末尾调用初始宏。 for the initial macro: 对于初始宏:

Sub checker()
Last = Cells(Rows.Count, "K").End(xlUp).Row
For i = 1 To Last Step -1
    If (Cells(i, "K").Value) = "Merged" Then

        Call macro_x

    End If
Next I
Call macro_z
End Sub

for macro_x: 对于macro_x:

Sub macro_x()
'DO SOMETHING HERE

Call checker
End Sub

EDIT: 编辑:

For i = 1 To Last Step -1

First thing I see is "merged" in your cell doesn't start with capital letter but in your code does. 我看到的第一件事是您单元格中的“合并”不是以大写字母开头,而是在您的代码中。

So please change to this. 因此,请更改为此。

Last = Cells(Rows.Count, "K").End(xlUp).Row
For i = Last To 1 Step -1
    If (Cells(i, "K").Value) = "merged" Then

        Call macro_x

    End If
Next I

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM