【问题标题】:VBA Table For Each If Then Loop - text repeat每个 If Then 循环的 VBA 表 - 文本重复
【发布时间】:2019-10-29 09:09:27
【问题描述】:

我需要一个代码来查看表格中的一列,如果文本中有某个字符串,则需要在另一列中输入新文本。

因此,查看 A 列(服务子类型),根据 A 列在 B 列(产品类别)中输入文本。这就是我目前所拥有的。

Dim productsubtype As Range

For Each productsubtype In Range("RawData[Service Sub Type]")
    If productsubtype.Value = "Training" Then
    Range("RawData[Product Category]").Value = "Education"

    End If

Next productsubtype

但是发生的情况是,它只是用“教育”填充所有 B 列,而不管 A 列中的内容是什么。我做错了什么?

【问题讨论】:

  • Range("RawData[Product Category]") 指的是整个列。如果您已经知道这些列,我会使用productsubtype.Offset(,1).Value = "Education"
  • 为什么这不能是IF 列中的[Product Category] 公式? =IF([Service Sub Type]="Training", "Education", "???")?
  • 或者更好的是,有另一个表将“服务子类型”映射到“产品类别”,并且让其他列只是一个查找公式。
  • @BigBen 我不知道为什么,但这样做完全解决了我的问题。两天的研究...谢谢!
  • “一个巨大的 if-then 序列”一遍又一遍地在同一个表达式上,闻起来非常非常像一个非常易于管理的查找表的工作。

标签: vba if-statement foreach


【解决方案1】:

正如 Mathieu 所建议的,您应该尽可能使用查找表,而不是冗长的 if 语句。

可能并不总是那么简单 if this then that,但是您应该能够使用查找表消除大部分 if 语句,并仅使用一些 if 语句来处理真正重要的事情。

话虽如此,使用您的示例并添加一个查找表(在我的示例中,我将其命名为 lookupTable),这应该为您提供一个起点:

Option Explicit

Sub lookupValues()

Dim arrData As Variant: arrData = Range("RawData") 'declare and allocate your table to an array
Dim arrLookup As Variant: arrLookup = Range("lookupTable") 'declare and allocate your lookup table to an array
Dim R As Long, X As Long

For R = LBound(arrData) To UBound(arrData) 'for each row in your data
    For X = LBound(arrLookup) To UBound(arrLookup) 'for each row in the lookup table
        If arrData(R, 1) = arrLookup(X, 1) Then 'if there is a match
            arrData(R, 2) = arrLookup(X, 2) 'allocate the value to the array
            Exit For 'value found, check next
        End If
    Next X
Next R

Range("RawData") = arrData 'put the values back into the table

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多