Вопрос

I've got a table and one of its column is kind of attributes of item. One item can have many attributes, and all of them are stored in one cell per each item, in seperate lines of text. I want to make script that enlist all the attribute types I've used so far and save that list in the second sheet. It propably cannot be achieved by standard formulas, so I assume the need to use VBA. I never used VBA before and don't know how to do this task. Also I can't find any reference of this language. I'm using MS Office 2007.

Это было полезно?

Решение

Sub export()
Dim cell As Range
Dim i As Long, j As Long
Dim var() As String
j = 1
For Each cell In Sheets(1).Range("a1:a10")
    Var = Split(cell, vbLf)
        For i = 0 To UBound(Var)
            Sheets(2).Range("a" & j).Value = Var(i)
            j = j + 1
        Next i    
Next cell
End Sub

My example loops all the cells in the range a1:a10 of sheet1. Adapt it to your needs. Each cell is splitted on linefeed and each row copied in the second sheet.

Другие советы

Here is a modified version of @nick rulez's great answer that uses a dictionary object, allowing you to exclude all duplicates.

Sub export()

Dim cell As range
Dim i As Long, j As Long
Dim var As Variant
Dim dictionary As Object
Set dictionary = CreateObject("scripting.dictionary")

On Error Resume Next
j = 1
For Each cell In Sheets(1).range("a1:a10")
    var = Split(cell, vbLf)
    For i = 0 To UBound(var)
        dictionary.Add var(i), 1
        j = j + 1
    Next i
Next

Sheet2.range("A1").Resize(dictionary.count).Value = _
Application.Transpose(dictionary.keys)

End Sub

How it works: It does the same thing as nick's but instead of writing each split entry to sheet2, it adds the entries to a dictionary file. Since a dictionary won't allow 2 keys of the same value, it skips dupes (you need that on error resume next though). Dictionary comes with the ultra-cool ability to transpose the array of keys, so at the end, I just copy the whole list over in one move.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top