Reusing /copying Macros from a file to another file - excel

I have an issue where I take data from multiple files and copy it into my current file. I work with the data and now I need to create a new File that contains the macros and the "style" from one of the import files and the new data I created.
So basically I take a file, delete all data from it. Then take my data and paste it into the file. Later I save the combinations of macros from old file and new data into a new file with which is created with the name "save as dialog."
So far I have a working import for all of the files and also my work on the data is doing great. Only this export is missing.
My idea would be to make the Path of the file public during the import and then during the import file use this path to do the following:
copy this file,
delete all data besides the macros and buttons
copy my data into it.
open the "save as dialog and let the user choose a name and the location where to save it.
However, I have absolutely no idea how something like this could be done in terms of code. Some code examples with explanations would be all I need I hope that I can then tailor it to fit my needs.
This is the code I tried so far but it's just a regular "save my current file" that doesn't include any macros from another file or takes another file as basis.
Sub DateiSpeichern()
Dim StandardPfad As String
Dim ExportBlatt As Worksheet
Dim NeueDatei As Workbook
StandardPfad = "C:\X"
Set NeueDatei = Workbooks.Add
ThisWorkbook.Sheets("Test").Copy Before:=NeueDatei.Sheets(1)
Application.DisplayAlerts = False
Sheets(2).Delete
Application.DisplayAlerts = True
'displays the save file dialog
StandardPfad = Application.GetSaveAsFilename(FileFilter:= _
"Exceldateien (*.xlsx), *.xlsx", Title:="Datei speichern", _
InitialFileName:="")
NeueDatei.SaveCopyAs Filename:=StandardPfad
NeueDatei.Close savechanges:=False
End Sub
Hello,
here is my first attempt of coding it. It doesnt work but i hope I got atleast the right idea.
Sub DateiSpeichern()
Dim StandardPfad As String
Dim ExportBlatt As Worksheet
Dim NeueDatei As Workbook
Dim VorlagenDatei As Workbook
'Sets a default directory
StandardPfad = "C:\Test"
'opens the dialog to choose the template file.
Set VorlagenDatei = Workbooks.Open(StandardPfad)
StandardPfad = Application.GetSaveAsFilename(FileFilter:= _
"Exceldateien (*.xlsx), *.xlsx", Title:="Datei speichern", _
InitialFileName:="")
'copies the selected file (something is wrong here i would assume)
VorlagenDatei.SaveCopyAs Filename:=StandardPfad
'copies my worksheet (Test) into the newly generated (copied) file. Here I need to somehow specifie the range where it is copied to.
ThisWorkbook.Sheets("Tires").Copy Before:=NeueDatei.Sheets(1)

Related

Using VBA to browse to import data beneath existing data in Excelsheet [duplicate]

I am trying to open an excel file in a folder of excel files using VBA. I direct my code to take the end user straight to the folder and allow him to choose the file from the dialog box. But I am not able to open the file even after selecting it from the dialog box.
My understanding of the problem is - I am missing out on the Command to open the file after selecting it.
Here is my Code,
thisYear = Year(Date)
'change the display name of the open file dialog
Application.FileDialog(msoFileDialogOpen).Title = _
"Select Input Report"
'Remove all other filters
Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Excel Files Only", "*.xls*")
'Select the start folder
Application.FileDialog(msoFileDialogOpen _
).InitialFileName = "\\driveA\Reports\" & thisYear & ""
Please kindly share your thoughts. Thanks.
I assume that you only let selecting one file (i.e. AllowMultiSelect = False).
Dim file As String
Dim myWbk As Workbook
file = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Set myWbk = Workbooks.Open(file)
First line gets the path of the selected file and then second line opens it. Add this to the end of your code.

Opening a Word file

I would like to open my Word file (to make the changes then save it under different name).
I can't open my file.
My first code:
Sub RamsOpen2()
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\Users\mariuszk\Desktop\cf10\RAMS.docx"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
VarResult = Doc.GetSaveAsFilename( _
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP",
initialvalue:="InitialDocument")
End Sub
which comes from here:
EXCEL VBA to Open Word, Edit and Saveas in the specified location.
This is roughly what I want to do with my Word file, however question is on the first step.
I have read here, that it is a common problem. VBA Excel - Unable to open existing Word Document file
I found a closer answer to my situation here: Excel macro - open specific word file
Following the advice from this query I mounted the following code:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
'Copy all data from Design
Sheets("Frontsheet").Select
Range("D18").Copy
' Tell Word to create a new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs filename:=ThisWorkbook.path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
End Sub
but the problem is the same.
Another answer is here: Excel VBA to Open Multiple Word files in a loop
but I don't want to open all Word documents in the folder.
This simple solution: VBA to open Excel or/and Word Files
also brings the same error.
As Fink pointed out in the comments your file icon looks like your file is a docm file. Since icons are chosen by file extensions there is only one solution: Check if you have file extensions turned invisible in Explorer (https://fileinfo.com/help/windows_10_show_file_extensions).
Your file is obviously called RAMS.docx.docm but you cannot see the file extension .docm.
Checkout if the following works
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx.docm")
or turn on your file extension view and rename the file.

Insert an Object into an Excel Worksheet

I would like to insert an Excel document into an Excel worksheet. I can do this manually by the following steps;
Insert / Text / Object / Create From File (tick Display as Icon) / Browse.
I then select the file and insert the document.
I would like to do this via a macro. (The recorder won't let you record it.)
This code I have basically is Insert / Text / Object
Sub ShowInsertObj()
Application.Dialogs(xlDialogInsertObject).Show
End Sub
I would like to add code so that a directory (lets say C:\temp) will automatically be selected and display as icon will be ticked - instead of applying the above steps.
Not sure if exactly what you wanted is possible, but you might want to use GetOpenFilename and .OLEObjects instead of xlDialogInsertObject.
Sub ShowInsertObj()
Dim Fl As Variant
Dim Filename As String
'Set your drive
ChDrive "C:"
ChDir "C:\temp"
'Grab your file filtered for Excel files
Fl = Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls; *.xlsm),*.xls;*.xslm")
If Fl = False Then Exit Sub
' To display the filename only and not the path
Filename = Mid$(F1, InStrRev(F1, "\") + 1, Len(F1))
'Add as object to the worksheet
Sheet1.OLEObjects.Add Filename:=Filename, Link:=True, DisplayAsIcon:=True, IconFileName:="EXCEL.EXE", IconIndex:=0, IconLabel:=Filename
End Sub
Note: I used FileFilter since you said you wanted to insert an Excel file

Export into a copied file

I will first tell you what I want to do, maybe that makes finding a solution easier. I want to export a file (after changing it) into a file that uses macro buttons etc on it's own. The problem is I cant delete said file.
My current solution is as follows: I use a "open file" Dialog so the user tells me the Excel that should be used as a template. VBA then should copy this file (the destination is once again given by a save file dialog) and then delete the used range in the new file and copy the values in this new file.
So there are 3 files Involved.
A: Current file with changed data and the macro I am doing right now.
B: Template File with macros.
C: New File that should be created with the macros from B and the
Data from A
So far I have this code that opens B and and copies it (i guess) it. My primary issue is how do I access the newly created file now. I assume I can somehow store it as a variable. Something like X = Path the user just selected in the save file dialog?
The deleting and inserting Data afterwards should be rather simple I guess/hope.
I hope you guys can help me and thanks a lot in advance :)
Here is my code so far:
Dim StandardPfad As String
Dim ExportBlatt As Worksheet
Dim NeueDatei As Workbook
StandardPfad = "C:\XYZ"
' ExportBlatt = Worksheets("Blatt1")
Set NeueDatei = Workbooks.Add
ThisWorkbook.Sheets("Blatt1").Copy Before:=NeueDatei.Sheets(1)
Application.DisplayAlerts = False
Sheets(2).Delete
Application.DisplayAlerts = True
' displays the save file dialog
StandardPfad = Application.GetSaveAsFilename(FileFilter:= _
"Exceldateien (*.xlsx), *.xlsx", Title:="Vorlagen Datei auswählen", _
InitialFileName:="")
NeueDatei.SaveCopyAs Filename:="C:\Test\CopyBook.xls" 'Hier Speicherort angeben
NeueDatei.Close savechanges:=False
Either I`m missing something in your question, or... Isn't this StandardPfad enough?
It needs a bit more error handling if the user cancel's the selection, but that's your X = Path the user just selected in the save file dialog
' displays the save file dialog
StandardPfad = Application.GetSaveAsFilename(FileFilter:= _
"Exceldateien (*.xlsx), *.xlsx", Title:="Vorlagen Datei auswählen", _
InitialFileName:="")
NeueDatei.SaveCopyAs Filename:=StandardPfad

VBA data transfer from one workbook to another, data type mismatch error

I'm new to VBA, but learning. I've written most of the following code myself, some of it was inherited. My goal here is to loop through multiple text files (these each contain a unique set of raw data) and copy (or in some other way transfer) that data into an analysis template that I've made which will then be "saved as" with the same filename as the raw data text file. I've been working on this for several days and have done a significant amount of searching to get this far, however, I'm currently stuck with a "Run-time type '13' error - mismatch data type" that I don't understand so I don't know how to get past it. The error is # "Data.Sheets(Sheet1).Range("A1:G180000").Copy. If I comment out the aforementioned line and the one that follows it and use the line above ("Template.Sheets(Sheet1).Range("A1:G180000").Value...") I still get the same error. My code is posted below and any help is very much appreciated. Thanks :)
Sub Shift_Load_Data_Plotter_Template()
'Josh Smith
'12/27/2013
'Shift Load Data Plotter Template
'This macro will bring up the Open dialog box so you can open multiple text files and analyze them using the Shift Load Data Plotter Template
'Brings up the Open window so you can select multiple excel files to import
Dim fn As Variant, f As Integer
Dim FileName As String
'Data is the source workbook and Template is the destination workbook
Dim Data As Workbook
Dim Template As Workbook
fn = Application.GetOpenFilename("Text files,*.txt", _
1, "Select One Or More Files To Open", , True)
If TypeName(fn) = "Boolean" Then Exit Sub
'the line below was modified from from just "workbooks.open "Z:\..." to "Set Template = Workbooks.open..."
'opens the Shift Load Data Analyzer Template workbook and sets the "Template" variable equal to said workbook
Set Template = Workbooks.Open("Z:\General Reference, Tools\Shift Load Data Analyzer Template.xlsx")
For f = 1 To UBound(fn)
'the line below was modified from just "workbooks.open fn(f)" to what it shows now
'sets the "Data" variable equal to the workbook which contains the data from the text file
Set Data = Workbooks.Open(fn(f))
FileName = ActiveWorkbook.Name
'Data.Activate
'Template.Sheets(Sheet1).Range("A1:G180000").Value = Data.Sheets(Sheet1).Range("A1:G180000").Value
Data.Sheets(Sheet1).Range("A1:G180000").Copy
Template.Sheets(Sheet1).Range("A1").PasteSpecial (xlPasteValues)
'the line below used to be "ActiveWorkbook.SaveAs..."
Template.SaveAs FileName:="Z:\" & FileName & ".xlsx"
Data.Close
Next f
End Sub
The line:
Data.Sheets(Sheet1).Range("A1:G180000").Copy
Should probably read as follows:
Data.Sheets("Sheet1").Range("A1:G180000").Copy
You need quotation marks around the sheet name if you're referring to the name (the Sheets() function is looking for the sheet name you see on the tab in Excel, not the Sheet1, Sheet2, Sheet3, etc. you see in the VBA screen). Otherwise you could write it like this:
Data.Sheet1.Range("A1:G180000").Copy
Try changing it to:
Data.Sheets(1).Range("A1:G180000").Copy
Template.Sheets(1).Range("A1").PasteSpecial (xlPasteValues)

Resources