2014-02-24 50 views
3

我有一組數據(網站管理員工具搜索查詢),其是在Excel具有以下標題:如何根據自定義規則對excel項進行分組?

Query | Impressions | Clicks | Date

樣品谷歌電子表格here

我想在名爲Category的額外增加一個字段,並根據會針對搜索字符串A列自定義規則分類的所有查詢 例如:

if A2 contains the string 'laptop' then write 'laptop' on the category next to it

到目前爲止,我已經嘗試一個公式來做到這一點,但我不確定這是最簡單的方法。另外,如果有很多分類規則,公式會變得非常長且難以管理。

=IF(ISNUMBER(SEARCH("laptop",A2)),"laptop", 
    IF(ISNUMBER(SEARCH("notebook",A2)),"laptop", 
    IF(ISNUMBER(SEARCH("iphone",A2)),"phone", 
    IF(ISNUMBER(SEARCH("galaxy s",A2)),"phone", 
"other"))) 

您能否提供這樣做的更好的方法,我可以在一個表中的規則的格式如下:

Query_contains | Category_is

其中Query_contains將需要在要匹配的字符串列A從最初的表格和Category將是需要填寫到列D的值。

+0

'Vlookup'應該做的到底是什麼,你正在試圖做的.. 。第一列將是你期望在A列中的值,第二列將是類別,然後你只需要查看該2列表...讓我知道如果這沒有意義.... –

+1

@JohnBus​​tos在示例電子表格中查看數據,一個簡單的vlookup將不起作用。 – guitarthrower

+0

對不起,感謝@guitarthrower,我現在下載了工作表...現在發佈解決方案... –

回答

8

好的,我改變了你片有點....

假設所有的數據是單元格A1:C9,那麼您在單元格F1中加入如下表有:G5現在

Search_For: Category: 
laptop   Laptop 
iphone   Phone 
galaxy   Phone 
notebook  Laptop 

,在D2單元格,把下面的公式:

=IFERROR(INDEX(G$2:G$5,MATCH(TRUE,ISNUMBER(SEARCH(F$2:F$5,A2)),0)),"other") 

而且輸入爲數組公式意義,一旦你進入它,打CTRL + SHIFT + ENTER

然後,您可以將公式從單元格D2向下拖動,它應該給您所需的結果(當然,您可以根據需要增加列F & G中的列表)。

希望這樣做的竅門!

+0

+1好回答John! – guitarthrower

+0

您的答案獲勝! –

+0

謝謝你們兩位! - 這真的只取決於你是否想要VBA或公式......你的解決方案更有效率,但需要VBA ......只取決於你要尋找哪種解決方案。 –

3

這個小宏假設您的數據在Sheet1條你的規則是在工作表規則在列A & B:

Sub catagorize() 
    Dim s1 As Worksheet, s2 As Worksheet 
    Dim N1 As Long, N2 As Long 
    Set s1 = Sheets("Sheet1") 
    Set s2 = Sheets("rules") 
    N1 = s1.Cells(Rows.Count, "A").End(xlUp).Row 
    N2 = s2.Cells(Rows.Count, "A").End(xlUp).Row 
    For i = 2 To N1 
     v = s1.Cells(i, 1).Value 
     For j = 1 To N2 
      If InStr(1, v, s2.Cells(j, 1).Value) > 0 Then 
       s1.Cells(i, "D").Value = s2.Cells(j, "B").Value 
      End If 
     Next j 
    Next i 
End Sub 
1

對於第三個選項,您可以使用自定義公式。

我爲單獨的工作表上的類別創建了一個表格,然後將以下代碼插入到標準模塊中。

Option Explicit 

Function CategoryLookup(s_Query As String, Keyword_tbl As Range) 
    Dim rngKeywords As Range 
    Dim s_foundCategory As String 
    Dim b_CategoryExists As Boolean 
    b_CategoryExists = False 

    For Each rngKeywords In Keyword_tbl 
     If InStr(s_Query, rngKeywords.Value) <> 0 Then 
      s_foundCategory = rngKeywords.Offset(0, 1).Value 
      b_CategoryExists = True 
      Exit For 
     End If 
    Next rngKeywords 

    If b_CategoryExists = True Then 
     CategoryLookup = s_foundCategory 
    Else 
     CategoryLookup = "Other" 
    End If 
End Function 

然後在D2(您的類別列)插入式(然後可以將拖累)

=CategoryLookup(A2,categories!$A$2:$A$5) 
相關問題