【问题标题】:Nested Key word Loops structure Questions嵌套关键字循环结构问题
【发布时间】:2016-10-27 17:56:04
【问题描述】:

(我的程序做什么)

---------Code worksheet for program

想要填充B列中的每个单元格,并在E列中使用关联的“分配给名称”(以前当A列中的语句文本包含在关键字D列

中找到的颜色时填充原始数据

程序通过执行使用 Instr 函数的 嵌套循环 来运行。我设计的结构创造了一个机械化的匹配过程。程序用 INSTR 函数搜索关键字:在 父字符串 (mytext) 变量中使用的是要在其中搜索“子字符串”的字符串(“蓝色”) .

如果 InStr(MyText, "Blue") And Cells(y, 4) = "Blue" 那么 Cells(x, 2) = Cells(y, 5)

如果 A 列(语句)中的 (("Mytext" 'primary_string') 变量包含与子字符串匹配的文本 , "blue", 'substring')

AND 单元格 (y, 4) ="Blue"

如果满足上述这些条件,则代码将在 THEN 语句上执行

那么



我的程序问题

我的问题集中在如何最好地理解设计此代码的机制。我已经将程序放在一起,有时我在最终结果中更幸运并且想要提高知识。

循环命名结构- 理解我的程序使用嵌套循环(一个循环在另一个循环内执行)

1。我说 Dowhile (x,1)'col A satements' 是外循环是否正确?

2. 我说 Do While (y,4) 'Col D keyword' 是内循环是否正确?

3. 说 myText 'primary string' 正在搜索 'substring' "Blue" 中所述的文本是否正确?

如果 InStr(MyText, "Blue") And Cells(y, 4) = "Blue" 那么 Cells(x, 2) = Cells(y, 5)

循环结构问题(根据我的假设)

4. Y = y+ 1(内循环)是否在 x = x + 1(外循环)之前,因此它退出内循环(Col D 关键字)以检查 Col A 语句中的关键字短语)?

**5.**为什么要在y=y+1之后使用关键字Loop(就是启动循环)?

6. 为什么必须在 x=x+1 之后写 Y+2 / 这是应对循环下一次迭代的正确方法吗?我问,因为我们已经有 Y=Y+1 ...

7.为什么我们不必写 x=2

y = y + 1 环形 x = x + 1 y = 2 循环


代码结构 & 变量


A 列 - 语句(预填充)

B 列- 分配给(最初为空白列)

C 列 - 空白列

D列-关键字(包含彩色文字关键字)

E列-分配给(填充B列的名称-如果A列中包含的文本与D列匹配


(我的程序中的代码)


Sub search_color()

x = 2
y = 2

Do While Cells(x, 1) <> ""

MyText = Cells(x, 1)

Do While Cells(y, 4) <> ""

If InStr(MyText, "Blue") And Cells(y, 4) = "Blue" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Brown") And Cells(y, 4) = "Brown" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Orange") And Cells(y, 4) = "Orange" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Yellow") And Cells(y, 4) = "Yellow" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Pink") And Cells(y, 4) = "Pink" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "White") And Cells(y, 4) = "White" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Red") And Cells(y, 4) = "Red" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Purple") And Cells(y, 4) = "Purple" Then Cells(x, 2) = Cells(y, 5)

If InStr(MyText, "Black") And Cells(y, 4) = "Black" Then Cells(x, 2) = Cells(y, 5)

y = y + 1

Loop

x = x + 1

y = 2

Loop

End Sub

【问题讨论】:

  • 首先,尽量缩进代码,这样会更容易阅读。关于您的问题:1-您是对的。 2 - 你是对的。 3 - 您是在寻找确切的单词,还是它是MyText 中更大字符串的一部分。 4 - 你是对的。 5 - 开头的每个Do While 循环都调用Loop 在结尾处关闭它。 6 - 你想重置到内循环。 7 - 你使用x = x + 1 因为你想将外循环推进1。

标签: vba excel loops for-loop nested-loops


【解决方案1】:
子 search_color() 暗淡 x 长,y 长 x = 2 Do While Cells(x, 1) "" y = 2 Do While Cells(y, 4) "" 如果 InStr(1, Cells(x, 1).Text, Cells(y, 4).Text, vbTextCompare) 那么 细胞(y,5)=细胞(x,2) 退出做 万一 y = y + 1 环形 x = x + 1 环形 结束子

【讨论】:

    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2017-09-20
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多