在Cell中查找文本并将结果输出到单独的列

时间:2017-08-02 15:30:44

标签: excel

我的excel中的数据如下所示,一行一行,但是A列中的所有信息。

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 个答案:

答案 0 :(得分: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和C列。 D,然后根据相应的数组测试每个值,以决定如何对其进行排序:

Before&After

我真的不知道其他任何方法。如果其他人有更好的解决方案,请分享。

相关问题