0

Hiyall!

I am new to excel macros and vba however willing to learn. Recently I came up with an idea to make specific macro decribed in the topic. Let me explain:

INPUT:

1 list with template style and fill of columns (numbers and formulas) 2 list for lookup function 3 output list

PROCESS: -start loop -for i to end_column on list2 create new list with name =Ai from list2 copy columns from list1 after copying cells with formulas replace every x with =Bi from list2 -save list csv

Yet I have found only saving as .csv, though it casuses error in path, like "impossible path"

Sub SplitSheets2()
    Dim s As Worksheet
    Dim wb as Workbook
    Set wb = ActiveWorkbook
    For Each s In wb.Worksheets
        s.Copy
        ActiveWorkbook.SaveAs wb.Path & "\" & s.Name & ".xlsx", FileFormat:=24
End Sub

where can I find other pieces? And how to make path work?

============= 14h edit I came up with the following code, but it has errors and more questions in comments

Dim c As Range
For Each c In Sheets("reference").Range("A2:A4")
    Sheets.Add After:=ActiveSheet
    Sheets("List2").Name = "123" '123 to change onto =ref!R3A2b but have "out of range error"
    Sheets("temp").Select
    Range("A1:D3").Select
    Selection.Copy
    Sheets("123").Select 'how do I select =ref!R3C2 list againg w/o looking up its name on ref list?
    ActiveSheet.Paste
    Range("C2").Select
    Application.CutCopyMode = False 'dont know yet what does that mean, yet I was only changing formula
    ActiveCell.FormulaR1C1 = "=reference!R3C2+1"
    Selection.AutoFill Destination:=Range("C2:C3"), Type:=xlFillDefault 'idk also how Type:= appeared
    Range("D2").Select
    ActiveCell.FormulaR1C1 = "=reference!R3C3*2"
    Selection.AutoFill Destination:=Range("D2:D3")
    Range("D2:D3").Select
End Sub
JayJayAbrams
  • 195
  • 1
  • 16
  • it is not clear what you are trying to do. .... you mention 3 lists, but you have no code that operates on lists ... the PROCESS line makes no sense at all. please have a look at what you posted... the `pieces` that you mention, what are they supposed to do? ... what is the purpose of the `s.copy` command? – jsotola Oct 31 '17 at 02:22
  • @jsotola `s.Copy` will copy the specified worksheet to a new workbook, thus being the only sheet in that new workbook. (And that new workbook will be the `ActiveWorkbook` after the copy.) – YowE3K Oct 31 '17 at 02:32
  • Do your sheet names contain any of the following characters: `\ / : * ? " < > |`? – YowE3K Oct 31 '17 at 02:34
  • You are saving the workbook as `FileFormat:=24`. You should be using .SaveAs on an unsaved workbook and for an MS DOS CSV (the XlFileFormat enumeration constant xlCSVMSDOS or 24) you should not be adding any file extension. In fact, you should **never** add the file extension; just let Excel assign the correct one from the FileFormat parameter. btw, you probably want xlCSV, not xlCSVMSDOS. –  Oct 31 '17 at 02:39
  • the `for each` command is incorrectly formed – jsotola Oct 31 '17 at 03:11
  • @jsotola by pieces I have meant other parts of code which I had not found by that time. ashleedawg proposed good way to figure it out – JayJayAbrams Oct 31 '17 at 16:49
  • @YowE3K nope I tried to avoid usage of these, example of code was added in original post – JayJayAbrams Oct 31 '17 at 16:50
  • @Jeeped oh, thank you! In fact I have found that code somewhere over the internet, but I definetely will use .SaveAs next time. Where can I find examples? – JayJayAbrams Oct 31 '17 at 16:52
  • FWIW - your original code (after adding the obviously missing `Next`) worked for me. (I haven't looked at your latest code). The only problem with your original code is that, because my computer is set up with an association to open files with an `xlsx` extension using Microsoft Excel instead of a text editor, I couldn't just double-click the new file in Windows Explorer to check its contents - I had to drag and drop the file into a text editor to make sure it was correct. (You should really use "standard" extensions whenever possible, so use `csv` for Comma Separated Values files.) – YowE3K Oct 31 '17 at 18:53

2 Answers2

0

Record a macro while you do all of the steps you need to repeat (copying, pasting, entering formulas, saving, etc) and then it will be simple to modify the VBA generated for the macro, to add a loop.

Some tips & examples:

And then the loop could be added with a couple lines:

Dim c as Range
For Each c in Sheets("Sheet1").Range("A1:A10")

    ...(code to repeat here)
    ...(refer to list item as:  c.Value  )

Next c

Edit:

This code loops through all worksheets in the active workbook, and "exports" each one as a separate `.CSV' file, each named after worksheet it came from. A working .xlsm example can be downloaded from JumpShare here. (*Online viewer won't work with VBA.)

Sub MakeWorkbooksFromSheets()
'save each sheet to a new workbook (named after the sheet)

    Dim sht As Worksheet, this_WB As Workbook, new_WB As Workbook
    Dim savePath As String, saveFile As String
    Dim currentWB As String, copyCount As Integer
    Set this_WB = ActiveWorkbook 'create current-workbook object

    If this_WB.Path <> "" Then
        savePath = this_WB.Path  'output path will be same as current file's path...
    Else
        savePath = Application.DefaultFilePath '...unless current file isn't saved yet
    End If

    For Each sht In this_WB.Worksheets
        saveFile = sht.Name & ".csv"

        If Dir(savePath & "\" & saveFile) <> "" Then
            'skip this sheet (or you could change this to delete existing file instead)
            MsgBox "Skipping Sheet - File Already Exists: " & vbCrLf & savePath & "\" & saveFile
        Else
            sht.Copy 'create new workbook, activate it, and copy sht to it
            Set new_WB = ActiveWorkbook 'create output worksheet object

            new_WB.SaveAs Filename:=savePath & "\" & saveFile, FileFormat:=xlCSVUTF8 ' save new file as CSV, or instead you could...

            copyCount = copyCount + 1

            new_WB.Close savechanges:=True 'close new workbook (remove this line to keep it open)
            Set new_WB = Nothing 'free memory of new_workbook object
        End If

    Next
    Set this_WB = Nothing 'discard current-workbook object
    MsgBox copyCount & " sheets copied to new CSV's in folder:" & vbCrLf & savePath
End Sub

Related reading:

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • thank you for your links and code example! They are very useful. Yet after recording marco and trying to change it I have encountered problems. I have added them into original post ed 14 hours ago @ashleedawg – JayJayAbrams Oct 31 '17 at 16:47
  • On SplitSheets2 add a line before the SaveAs line : `debug.print wb.Path & "\" & s.Name & ".xlsx `and if thats giving you a valid filename. More to come after that – ashleedawg Oct 31 '17 at 18:10
  • @JayJayAbrams So, I attempted to elaborate on my last comment more while multitasking at work, and wrote a long & detailed response with code samples, using Stack Overflow's Android App, when I discovered a _wonderful bug_ where if I turn my phone sideways to "landscape" and then scroll at all, it *logs me out, disposing of my entire unsent post* ... Tried another time, same thing happened. So after I find the Meta section to report a bug I can get into more detail with your issue -- or have you found a solution? – ashleedawg Nov 01 '17 at 02:02
  • Yeah @ashleedawg! I have added answer post, code works but I have question about making proper look there. Can you take a look at it please? – JayJayAbrams Nov 01 '17 at 16:32
  • @JayJayAbrams "proper look"? – ashleedawg Nov 02 '17 at 02:07
  • my bad @ashleedawg . Wanted to say that one part of original idea was solved (copying and creating required lists) while others were not yet. Proper look imlplies final code with all ideas combined. – JayJayAbrams Nov 02 '17 at 02:13
  • @JayJayAbrams Actually, back up a but here. I don't mind helping you get started with coding (and it's good that you are hoping to _learn_ in the proces-- that goes far around here!) but I would need a better picture of exactly what you're trying to do. (1) What are you starting with? As I understand so far, you have a workbook with multiple sheets, that you want to use as a template? A screen shot would help if possible ? :-) (2) What do you need to end up with? As I understand, you want to copy the template to a new file? Am I close? A screen shot would help if possible. :-) – ashleedawg Nov 02 '17 at 02:15
  • Sure @ashleedawg ! (1) Some background: I am working with databases. Often one database should be transformed for later usage in different software which requires special format. At this specific task I am willing to massively create lists and export them so other software could massively import. (2) I'll try to post screenshot from my workspace or home. – JayJayAbrams Nov 02 '17 at 02:22
  • @JayJayAbrams I also work with databases but now I am more confused since I'm not sure how they are involve but yeah some screenshots should help! Before seeing you last comment I put together sample code to do what I _thought_ you meant... [code added to my Answer above] – ashleedawg Nov 02 '17 at 06:12
  • Sorry thats very rude of me but I was not able to reply or upload that day or the day after :< @ashleedawg Here is link to template I have with updated formula [link](http://jmp.sh/zjiVYX6) on "temp" list there are constant values with 2 colums of formulas and on ref - reference variables for each new list. Goal in creare new list with existing f-la in eg. D3 but change absolute cell and rest is same with autofill. I have added Cstr to remove n string and overwriting,deleting. Questions: how to assing cell=ref!$B$2+1+C2 and autochange abs cell? via string assing/ break and &"2+c" in the end? – JayJayAbrams Nov 04 '17 at 13:41
  • ps your code @ashleedawg works perfectly and fits my needs, I have slightly edited it in the link file. – JayJayAbrams Nov 04 '17 at 13:42
  • Again my bad in explaining things @ashleedawg by transiton or changing cells I've meant changing formula like =ref!$B$2+1+C2. Change absolute cell to like ref!$C$6 and change rest of formula 1+C2 to like C2/6*LOG(D2) etc. Moreover I'd like to know is there any way to just change abs cell and avoid typing whole formula in VBA macro? – JayJayAbrams Nov 04 '17 at 13:49
0

I ended up with following code and it works! Thank you all! But I have a question about loop;

Sub MarcoTemplate()
Dim c As Range
Dim n As String
For Each c In Sheets("ref").Range("A2:A3")
    n = c
    Vl = Application.WorksheetFunction.VLookup(n, Sheets("ref").Range("A2:D3"), 2, False)
    Worksheets.Add.Name = c
    ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.Count)
    Worksheets("temp").Range("A1:D3").Copy ActiveSheet.Range("A1")
    Range("C2").Select
    ActiveCell.FormulaR1C1 = "=ref!R2C2" + "+1"
    Selection.AutoFill Destination:=Range("C2:C3")
    Range("D2").Select
    ActiveCell.FormulaR1C1 = "=ref!R2C2" + "*4"
    Selection.AutoFill Destination:=Range("D2:D3")
    Range("G2").Select
    ActiveCell.FormulaR1C1 = Vl
Next c
End Sub

How do I make transition between formula cells? Example:

ActiveCell.FormulaR1C1 = "=ref!R2C2" + "+1"

Here I want to change ref!R2C2 to ref!R2C(c-row number) or something else like c+=1 adding 1 row or 1 column for each new c

@ashleedawg @YowE3K

JayJayAbrams
  • 195
  • 1
  • 16
  • `"transition between formula cells"`- do you mean to Select different cells? If you want to "move down" and select the cell 1 row down, you could use: `Cells(ActiveCell.Row + 1, ActiveCell.Column).Select` or to move the selection 4 columns to the right, you could use: `Cells(ActiveCell.Row, ActiveCell.Column+1).Select` – ashleedawg Nov 02 '17 at 02:29