4
votes

I have an excel sheet which has some huge data. Data is organized as follows, A set of 7 columns and n rows; as in a table, and 1000s of such tables are placed horizontally with an empty column to separate. A screenshot is below..

enter image description here ...

I just want to have data of every 'table' saved into a different file. Manually it would take ever! So, Is there a macro or something I would automate this task with. I am not well versed with writing macros or any VBA stuff.

Thanks,

3
Do you mean that you want each 'table' saved into it's own file, or all of them into the same file? - lnafziger
Yeah, I want each table saved to its own file. Sorry, I wasn't clear on that. - ViV
When you say "its own file" do you mean in a separate Excel spreadsheet, or do you want to save the data in some other format (CSV for example)? - assylias
I had to correct a typo in the middle of the previous version of this comment. You say each table is seven columns wide. Does that mean columns A and B are not to be saved? From the use of "n", I assume the tables are all different heights. If the table starting at C1 finishes on row 21, does the next table start at C23? If the table starting at K1 finishes on row 15, does the next table start at K17 or K23? What are the 1000s of files to be named? Will system generated names (F0001, F0002, F0003, etc) be acceptable? I do not think this is a difficult task but you must specify it fully. - Tony Dallimore
@assylias CSV preferable, but an Excel Spreadsheet will also do :) - ViV

3 Answers

6
votes

Tony has a valid point when he says

If the table starting at C1 finishes on row 21, does the next table start at C23? If the table starting at K1 finishes on row 15, does the next table start at K17 or K23?

So here is a code which will work in any condition i.e data is set horizontally or vertically.

DATA SNAPSHOT

enter image description here

CODE

'~~> Change this to the relevant Output folder
Const FilePath As String = "C:\Temp\"

Dim FileNumb As Long

Sub Sample()
    Dim Rng As Range
    Dim AddrToCopy() As String
    Dim i As Long

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    Set Rng = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants, xlTextValues)

    If Not Rng Is Nothing Then
        AddrToCopy = Split(Rng.Address, ",")

        FileNumb = 1

        For i = LBound(AddrToCopy) To UBound(AddrToCopy)
            ExportToSheet (AddrToCopy(i))
        Next i
    End If

    MsgBox "Export Done Successfully"

LetsContinue:
    Application.ScreenUpdating = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Sub ExportToSheet(rngAddr As String)
    Range(rngAddr).Copy

    Workbooks.Add
    ActiveSheet.Paste

    ActiveWorkbook.SaveAs Filename:= _
    FilePath & "Output" & FileNumb & ".csv" _
    , FileFormat:=xlCSV, CreateBackup:=False

    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True

    FileNumb = FileNumb + 1
End Sub

NOTE: The above code will work for cells with only Text Values. For cells with only Numeric Values you have to use

Set Rng = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants, xlNumbers)

And for AlphaNumeric Values (As in your question above), use this

Set Rng = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)

HTH

Sid

2
votes

As long as there is a blank row and a blank column around any datasets, this will use the AREAS() method to put them all in separate workbooks.

As per the prior example, it saves as CSV, but of course you can save it as you wish.

Option Explicit

Sub ExportDataGroups()
Dim fPATH As String, Grp As Long, DataRNG As Range

fPATH = "C:\Path\Where\I\Want\My\Files\Saved\"    'remember the final \
Application.ScreenUpdating = False

Set DataRNG = ActiveSheet.UsedRange

    For Grp = 1 To DataRNG.Areas.Count
        DataRNG.Areas(Grp).Copy
        Sheets.Add
        Range("A1").PasteSpecial
        ActiveSheet.Move

        ActiveWorkbook.SaveAs Filename:=fPATH & "-" & Format(Grp, "0000") & ".csv", _
            FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next Grp

MsgBox "A total of " & Grp & " files were created"
Application.ScreenUpdating = True

End Sub
2
votes

In your response to my comment you state: "File name, I never thought about it. Could be anything for now." From bitter experience I can tell you that dealing with thousands of files with system generated names is a nightmare. You need to fix the name problem now.

I am also nervous about AddrToCopy = Split(Rng.Address, ","). Rng.Address will be of the form: "$C$1:$I$16, $K$1:$Q$16, $S$1:$Y$16, $C18$I$33, $K$18:$Q$33, $S$18:$Y$33, ...". If you search the internet you will find sites that tell you that Rng.Address has a maximum length of 253 characters. I do not believe this is correct. In my experience, Rng.Address is truncated at a complete sub-range. My experimentation was with Excel 2003 but I have found noting on the internet to suggest this limitation has been fixed in later versions of Excel. You much check Rng.Address with your version of Excel! I am not familar with Jerry Beaucaire, although he offers an interesting solution. Sid Rout always produces excellent code. If there is a problem, I am sure they will be able to fix it.

However, the real purpose of this "answer" is to say I would split this problem into three. This has lots of advantages and no disadvantages of which I am aware.

Step 1. Create a new worksheet, TableSpec, with the following columns:

A      Worksheet name. (If tables are spread over more than worksheet) 
B      Range. For example: C1:I16, K1:Q16
C - I  Headings from table. For example, AAPL, Open, High, Low, Close, Volume, AdjClose 

Step 2. Check worksheet TableSpec; for example, are all table listed? Think about the file name and add column H to contain it. I read one of your comments to mean you would "AAPL" as the filename for the first table in which case you could set H2 to "=C2". Is "AAPL" unique? You could had a sequence number. There are lots of choices which you can think about before you generate any files.

Step 3. Worksheet TableSpec now gives all the information necessary to generate your files. You could delete most of the contents and test the file creation code on a couple rows.

I hope you can see advantages of this stepped approach, partcularly if your VBA is weak. Best of luck.