1

Below is a screengrab of a very basic version of the excel workbook I'm trying to create

screengrab

The goal is to have the a Button that does the following things:

  1. Clicking on the Button creates a copy of this workbook, including VBA

  2. The workbook needs to be saved in the same directory, with the directory not being specific

  3. The name of the new copied workbook needs to be taken from cells B6, then B7, then file extention . Ie. in this example it would be "VW Golf 3RTY568.xlsm"

  4. In this newly created "VW Golf 3RTY568.xlsm" file, I want to clear cell B2, B3 and B4 and cut&paste cell B6 and B7 to cell B3 and B4. This part I have already got working through recording a macro

  5. The final requirement is that the new "VW Golf 3RTY568.xlsm" workbook also has the same button element that performs step 1 to 4

So in short: clicking on the button needs to create a copy of the workbook (named after the Trade-in Car & License plate), and formats the cells so that the user can easily enter a new trade-in car and repeat the process by clicking the button.

The issue I am running into is in creating a copy of the workbook in the same directory, and ensuring that the copy (and all subsequent copies) have a functioning Button

This is my current code for creating a copy of the file, which already does not work correctly - it insteads create a copy in "/My Documents"

VBA Code:

Sub createnewWB()
    Dim thisWb As Workbook
    Dim newWBname As String
    
    newWBname = Range("B7")
    
    Set thisWb = ActiveWorkbook
    Workbooks.Add
    ActiveWorkbook.SaveAs Filename:=thisWb.Path & newWBname
    
End Sub


Sub buttoncalls()

Call createnewWB

End Sub
Filburt
  • 17,626
  • 12
  • 64
  • 115
TiesA
  • 11
  • 1
  • Does `newWBname` string contain extension? If yes you should add only the path separator: `Filename:=thisWb.Path & "\" & newWBname` – FaneDuru May 05 '21 at 12:49
  • If not extension: `Filename:=thisWb.Path & "\" & newWBname & ".xlsm"`. If you need the concatenation between B6 and B7, with a space in-between: 'newWBname = Range("B6").value & " " & Range("B7").value – FaneDuru May 05 '21 at 12:58

1 Answers1

1

Something like this:

Sub Test()

    'Code that starts with a . refers to Sheet1 (With...End With)
    'e.g. .Range("B3") refers to Sheet1, while Range("B3") refers to the activesheet.
    With ThisWorkbook.Worksheets("Sheet1")
        
        .Range("B2:B4").ClearContents
        .Range("B6:B7").Copy Destination:=.Range("B3")

        ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & .Cells(6, 2) & .Cells(7, 2) & ".xlsm"

    End With

End Sub

If the workbook path is being synced with one-drive then your path may end up starting https in which case wrapping ThisWorkbook.Path with the function provided in this post seems to sort it out: Excel's fullname property with OneDrive.
I found the post by @PeterGSchild worked best for me.

Darren Bartrup-Cook
  • 18,362
  • 1
  • 23
  • 45