选择具有多个条件的案例函数不循环

时间:2013-06-20 22:02:21

标签: vba excel-vba compiler-errors select-case excel

我是vba的新手,也是我第一次使用“Select Case”。简而言之,我试图通过查找“cust_num”列标题并遍历每一行来循环(行数将从一张纸更改为另一张),如果cust_num匹配特定行的条件,则“Barco”将被放入“公司名称”列下的同一行。

当我编译时,“Barco”仅被放置在第一行之下,因此看起来不会循环遍历每一行,下面的示例。

XX278        Barco
XX004   
XX004   
XX278   
XX004   
XX004   
XX278   
XX278   





Dim Nu As Range
    Dim cmpny As Range
    Dim v As Integer
    Dim y As Integer

    v = ActiveSheet.Rows(1).Find("customer_name", LookAt:=xlPart).End(xlDown).Count - 1 
'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

    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"
            End Select
    Next

1 个答案:

答案 0 :(得分:0)

使用@TimWilliams帮助我的代码现在可以使用了。这使用Select Case函数循环遍历指定的行并确定该单元格是否满足条件,如果是,则在条件单元格右侧的同一行插入名称(在本例中为cust_num)。 p>

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 
'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

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"
        End Select
Next