【问题标题】:Working with for each: at the end of the loop the result is not recorded使用 for each:在循环结束时不记录结果
【发布时间】:2018-02-01 13:22:08
【问题描述】:

我被困了大约一个小时:看起来我错过了一些东西。

我已经编写了上面的代码来操作数组中的文本。它的设计目的是从 keywordToProcess 中删除被忽略的关键字,这就是 j = "" 的意思。在那一行j = ""j 确实变成了空白,但成品i = join(i," ") 仍然有应该变成空白的单词。为什么?我不熟悉For Each-loop,也许我错过了一些重要的事情。

For Each i In keywordToProcess
    i = Split(i, " ")
    For Each j In i
        j = RemovePrurals(j)
    Next j
        For Each j In i
            For Each k In ignoreArr
                If j = k Then
                    j = ""
                End If
            Next k
        Next j
    i = Join(i, " ")
Next i

【问题讨论】:

  • 您永远不会将结果 (j = "") 存储在 i
  • 我该怎么做?

标签: vba foreach


【解决方案1】:

你正确地使用了For Each ... Next。问题是你混淆了变量。 (我认为keywordtoprocess 是一个字符串数组。)然后For Each 中的iSingle String。在下一行i 将类型更改为String ArraySplit。然后在最后一行中,您使用JoinString Array i 创建一个Single String。但是在下一步中,您将使用Next ... For Each 覆盖i,在其中将下一个Single String 值分配给i。 VBA 允许您这样做,但您应该避免这样做。所以我建议:使用Option Explicit,声明你的变量,并在编码之前进行设计。请记住,每个变量背后都有物理内存单元。

编辑:我会这样编码(假设keywordtoprocess是一个字符串数组)

' Dim keywordtoprocess() As Variant
Dim sKW As String      ' keyword
Dim asBuf() As Variant ' string buffer for current keyword split to pieces
Dim sK As String       ' for keywords to be ignored
Dim i As Long          ' loop

    For Each sKW In keywordtoprocess
        asBuf = Split(sKW, " ")
        For i = LBound(asBuf) To UBound(asBuf)
            asBuf(i) = RemovePrurals(asBuf(i)) ' this is the way to change value
            For Each sK In ignoreArr
                If asBuf(i) = sK Then
                    asBuf(i) = vbNullString
                End If
            Next sK
        Next i
    Next sKW
    sK = Join(asBuf, " ")
    Debug.Print sK

请注意,更改循环变量不会更改真实数据。请参阅我在 RemovePrurals 的建议。无论如何,您最好避免更改循环变量,即使可以。

【讨论】:

  • 感谢您的回答。您能否详细解释一下倒数第二行的 i 与第二行的 i 有何不同?
猜你喜欢
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2011-04-29
相关资源
最近更新 更多