2017-08-02 34 views
0

我有數據,但在A列的所有信息查找文本在Excel中,看起來像下面,一行一行地分開的欄目

A 
--------------------- 
Yellow Car Small 
--------------------- 
Red Bike Big Big 
--------------------- 
Big Yellow Car 
--------------------- 
Yellow Big Motorbike 

我需要輸出到B柱,有什麼它是什麼顏色,C是多大,D是什麼類型。

我從哪裏開始?

香港專業教育學院做了一個列表,每個類別

Colour | Type  | Size 
-------|-----------|------ 
Blue | Car  | Small 
-------|-----------|------ 
Yellow | Bike  | Big 
-------|-----------|------ 
Red | Motorbike | Large 

,但我想我失去了一些東西。

回答

1

所以,這有點複雜,因爲VBA不知道顏色是什麼,車輛是什麼,或者尺寸是多少,所以你需要告訴它。不幸的是,你真的可以做到這一點的唯一方法是通過在預先設定的陣列,而您可以引導它放置值:

Sub splititup() 

Dim myarray() As String 

For i = 1 To 4 'or use lastrow for a dynamic range 
    myarray = Split(Range("A" & i).Value, " ") 
    Range("B" & i).Value = myarray(0) 
    Range("C" & i).Value = myarray(1) 
    Range("D" & i).Value = myarray(2) 
Next i 

Dim mycolors() As Variant, myvehicles() As Variant, mysizes() As Variant 

mycolors = Array("Red", "Yellow", "Blue", "Green", "Orange", "Purple") 
mysizes = Array("Small", "Medium", "Large", "Big") 
myvehicles = Array("Boat", "Car", "Bike", "Motorbike", "Truck") 

'color, size, type 

Dim Value1 As String, Value2 As String, Value3 As String 

For i = 1 To 4 
    Value1 = Range("B" & i).Value 
    Value2 = Range("C" & i).Value 
    Value3 = Range("D" & i).Value 

    If Not IsInArray(Value1, mycolors) Then 
     If IsInArray(Value1, mysizes) Then 
      Range("C" & i).Value = Value1 
     Else 
      Range("D" & i).Value = Value1 
     End If 
    Else 
     Range("B" & i).Value = Value1 
    End If 

    If Not IsInArray(Value2, mycolors) Then 
     If IsInArray(Value2, mysizes) Then 
      Range("C" & i).Value = Value2 
     Else 
      Range("D" & i).Value = Value2 
     End If 
    Else 
     Range("B" & i).Value = Value2 
    End If 

    If Not IsInArray(Value3, mycolors) Then 
     If IsInArray(Value3, mysizes) Then 
      Range("C" & i).Value = Value3 
     Else 
      Range("D" & i).Value = Value3 
     End If 
    Else 
     Range("B" & i).Value = Value3 
    End If 

Next i 

End Sub 

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean 
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) 
End Function 

這從A列拆分值成列B,C & d,然後測試每個值反對它的相應的陣列,以決定如何對它進行排序:

Before&After

我真的不知道任何其他方式來做到這一點。如果其他人有更好的解決方案,請分享。

相關問題