【问题标题】:Excel 2007 VBA If Then Statement Using Multiple CriteriaExcel 2007 VBA If Then 语句使用多个条件
【发布时间】:2013-06-19 21:14:53
【问题描述】:

我有一个多重 IF 条件语句,如果有的话,应该返回指定的值。当我编译下面的代码时,它返回:

cust_num    company name

XX278   
XX004       Barco   
XX004   
XX278   
XX004   
XX004   
XX278   
XX278   

我的意图是让 cust_num "XX278" 在公司名称下也返回 "Barco",因为它与条件 2 匹配,但由于某种原因,它跳过了它,并且似乎没有像我预期的那样循环遍历所有行(例如,所有 XX004、XX278 cust_num 都应该有公司名称)。为什么我的代码没有遍历每一行?任何帮助将不胜感激。谢谢!

Dim v As Integer
Dim y As Integer

y = 0
condition1 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX004")
condition2 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX278")
condition3 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX318")

v = ActiveSheet.Rows(1).Find("customer_name", LookAt:=xlPart).End(xlDown).Count

For y = 0 To v
If condition1 Or condition2 Or condition3 Then ActiveSheet.Rows(1).Find _
    ("company name",LookAt:=xlPart).Offset(1 + v, 0) = "Barco"
Next

【问题讨论】:

  • 我在那里看不到任何问号。问题在哪里?
  • 抱歉,为什么代码会越过第一个真条件并捕获第二个真条件?
  • 感谢@PowerUser,这让我走上了正轨。我尝试了代码,但它给了我相同的结果。我会继续努力,如果有人能提供帮助,那就太好了!
  • 实际上,整个事情看起来比它需要的复杂得多。为什么不只是一个 vlookup()?
  • 我认为这行不通。 Cust_num 被随机分配为我正在浏览的工作表上的列标题。单个公司最多有 30 个不同的 cust_num,因此有 30 个不同的条件。必须有更好的方法,但我对此很陌生,可能在我头上:(

标签: excel vba if-statement for-loop


【解决方案1】:

设置一个在列表中包含所有 Cust_Num 的工作表,其右侧有相应的 Company Name。如下图所示:

然后,一旦您完成了所有设置,请使用 excel 中的 VLOOKUP 函数。这是我的示例公式:

=VLOOKUP(A3,LookUp!$A$1:$B$9,2,FALSE)

VLOOKUP 第一部分中的A3 是对行中Cust_Num 的单元格引用。

LookUp!$A$1:$B$9 是保存您查找值的数组。

2 会将VLOOKUP 的结果定向到第二列,在本例中为您手动输入的Company Name

FALSE 只会返回完全匹配的内容。

然后我只需将这个公式拖下来,我就得到了这个:

*注意:*如果您需要帮助获取列表中每个Cust_Num 的列表,您可以执行以下操作:

选择所有Cust_Num 的列表,然后在数据选项卡的功能区中,选择高级过滤器:

然后在窗口中:

  1. 选择Copy To Another Location
  2. 输入Copy To 范围作为查找表
  3. 确保选中Unique Records Only 的复选框

然后,您只需将这些值填入对应的Company Names 一次,然后如前所述使用VLOOKUP

如果首选 Find 方法,您可以使用:

Sub AddAllNames()

Call AddCompanyNameNextToCust_Num("37004", "Varco")
Call AddCompanyNameNextToCust_Num("44278", "Varco")
Call AddCompanyNameNextToCust_Num("44318", "Varco")
Call AddCompanyNameNextToCust_Num("12345", "Name1")
Call AddCompanyNameNextToCust_Num("12344", "Name1")
Call AddCompanyNameNextToCust_Num("12346", "Name1")
Call AddCompanyNameNextToCust_Num("98765", "Name2")
Call AddCompanyNameNextToCust_Num("56789", "Name2")
Call AddCompanyNameNextToCust_Num("89756", "Name2")

End Sub


Function AddCompanyNameNextToCust_Num(strCust_Num As Variant, strCompanyName As String)

    Dim rngCust_nums As Range, rngFoundCell As Range, rngFirstCellFound As Range
    Dim rngCust_NumsColumn As Long
    Dim boolFinished As Boolean

    'Get Column With header "cust_num"
    rngCust_NumsColumn = WorksheetFunction.Match("cust_num", Rows(1), 0)

    'Set The Search range to column from last line
    Set rngCust_nums = ActiveSheet.Columns(rngCust_NumsColumn)


    'Get the first matching value of Cust_Num (passed into sub)
    Set rngFoundCell = rngCust_nums.Find(What:=strCust_Num, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)

    'Check to make sure a match was found/ "Not Nothing"       
    If Not rngFoundCell Is Nothing Then

        'Save the First Found Cell 
        Set rngFirstCellFound = rngFoundCell

        'Add Company Name One Column to the Right of First Found Cust_Num
        rngFoundCell.Offset(, 1).Value = strCompanyName

        'Start Looping a "FindNext" 
        Do While boolFinished = False
            'Set each new match into an overwriting Variable
            Set rngFoundCell = rngCust_nums.FindNext(After:=rngFoundCell)

            'Make sure the match is "Something"
            If Not rngFoundCell Is Nothing Then
                'Make sure We have not gone through the whole list and that we
                'are not back to the begining
                If rngFoundCell.Address = rngFirstCellFound.Address Then Exit Do
                'If a new match is found and is not the starting point then add 
                'the company name in the next column
                rngFoundCell.Offset(, 1).Value = strCompanyName
            Else
                'When nothing is Found End loop
                boolFinished = True
            End If

        Loop

    Else 'If not even one match was found
        MsgBox strCust_Num & " not Found"
    End If


End Function

【讨论】:

  • @ZacharySmith 我也添加了一个 VBA 版本,如果喜欢的话,它的工作原理与您的原始版本类似,但不是循环所有单元格,而是循环匹配的单元格。
【解决方案2】:

看起来您的条件甚至在循环开始之前就已被评估(即仅在 y=0 时评估,而不是在循环期间评估。)

我发现你的代码有一些问题,但你可以试试这个(不能保证,我现在不能测试这个):

Dim v As Integer
Dim y As Integer
Dim condition1 as boolean
Dim condition2 as boolean
Dim condition3 as boolean

y = 0

v = ActiveSheet.Rows(1).Find("customer_name", LookAt:=xlPart).End(xlDown).Count

For y = 0 To v
    condition1 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX004")
    condition2 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX278")
    condition3 = (ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart).Offset(1 + y, 0) = "XX318")
    If condition1 Or condition2 Or condition3 Then ActiveSheet.Rows(1).Find _
        ("company name",LookAt:=xlPart).Offset(1 + v, 0) = "Barco"
Next

【讨论】:

    【解决方案3】:

    通过其他帖子的帮助,我找到了一种更简单的方法来评估多个标准,而不是使用 If Then 语句,我使用了我发现效率更高的 Select Case。下面的代码将在一行中查找 cust_num,如果满足这种情况,公司名称将插入到同一行的右侧一列中。

    Dim Nu As Range
    Dim cmpny As Range
    Dim v As Integer
    Dim y As Integer
    
    v = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 'count number of rows
    
    
    Set Nu = ActiveSheet.Rows(1).Find("cust_num", LookAt:=xlPart) 'set Nu = cust_num column header
    Set cmpny = ActiveSheet.Rows(1).Find("company name", LookAt:=xlPart) 'set cmpny = company name column header
    
    For y = 0 To v 'loop through each row
    
        Select Case Nu.Offset(1 + y, 0).Value 'row 1 + y of "cust_num"
            Case "XX004", "XX278", "XX318" 'if "cust_num" row = these #'s
                cmpny.Offset(1 + y, 0).Value = "Barco" 'Then corresponding row under "company name" column = "Varco"
    Next
    

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2022-01-22
      • 2013-04-11
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多