Deleting and creating a new workbook with the same name - vba

I would like to create a new Workbook with the name 'Land-DE'. If the file already exists in the directory it must delete it automatically before creating a new one. I've tried using the following code but it is not working.
Sub createwb()
Workbooks.add
Dim FSO
Dim path As String
Set FSO = CreateObject("Scripting.FileSystemObject")
set path = "D:\Job\Land-DE.xlsx"
If FSO.FileExists(path) Then
FSO.DeleteFile path, True
else
ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsX"
End If
End Sub

Why must it be deleted before save? Would it be enough:
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsx"
Application.DisplayAlerts = True

Have a look at the following. This will check if there is a file with the name defined in path and if so delete it before saving it again.
Sub Createwb()
Dim path As String
path = "D:\Job\Land-DE.xlsx"
If Dir(path) <> "" Then Kill path
ActiveWorkbook.SaveAs path
End Sub

Sub createwb()
Workbooks.Add
Dim FSO
Dim path As String
Set FSO = CreateObject("Scripting.FileSystemObject")
path = "D:\Job\Land-DE.xlsx"
If FSO.FileExists(path) Then
FSO.DeleteFile path, True
End If
ActiveWorkbook.SaveAs path
End Sub
Two things: Set is used for setting objects. The path there is just a string variable. Objects are a group of functions and variables, like that FSO object you create above it.
Next, you need to make sure you save after you delete it, and also that the last version of the save is not still open when you loop through again. If it is, you'll get permission denied for trying to save over a file that's currently open.

There are multiple problems with your code
set path = "D:\Job\Land-DE.xlsx" 'It is syntax error, you can only set object in VBA , string is not considered as object
FSO.DeleteFile path, True 'USE kill instead, better performance
ActiveWorkbook.SaveAs "D:\Job\Land-DE.xlsX" ' Do not user active keyword, always set the object
Here is the code :
Sub createwb()
Dim wbnew As Workbook
Set wbnew = Workbooks.Add
Dim path As String
path = "D:\Job\Land-DE.xlsx"
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(path) Then
On Error Resume Next
Workbooks("Land-DE").Close False ' Close the workbook if open
Kill path
wbnew.SaveAs path
Else
wbnew.SaveAs path
End If
End Sub

Related

Use files in a folder - exceptions VBA

I need to perform a certain task over some excel files located in subfolders (which are inside a folder). This task must exclude all those file's names that contain the letter "v".
I used file name length since the files I want to use have that length (file names with letter "V" have more than 28 characters). Here is my code.
Sub test()
Application.ScreenUpdating = False
Dim Fso As Object, objFolder As Object, objSubFolder As Object
Dim FromPath As String
Dim FileInFolder As Object
FromPath = "C:\Prueba"
Set Fso = CreateObject("Scripting.filesystemobject")
Set objFolder = Fso.GetFolder(FromPath)
For Each objSubFolder In objFolder.Subfolders
Dim wbk As Workbook
Dim Filename As String, File As Variant
Path = objSubFolder.Path
Filename = Dir(Path & "\*.xlsx")
For Each File In objSubFolder.Files
If Len(Filename) = 28 Then
Do something
wbk.Close True
Filename = Dir
End If
Next File
Next objSubFolder
ActiveWorkbook.Close savechanges:=True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This code works OK until it reaches a file with "V". It just stuck in that file (do nothing, which is good) and then goes to the next subfolder, ignoring all the remaining excel files.
I need some advice on how to deal with this.
thx

Open other application from vba

I am working on a macro to open a file(might already be open) and save with new name and then open the new file from vba in excel.
This file can Powerpoint,mathcad,visio, word etc..(can also be template files such as dotx etc..)
So my idea is that:
I first need to figure out if the application is open or not,
then I somehow need to figure if the file is open or not,
then save it with the new filename.
Open the new document
Go through the document and dumps custom variables into the database, populate custom variables from database(Not shown in code below, seperate module)
Activate the new document so that the user can edit it.
Public Sub saveAsVBADocument(filenameNew As String, fileNameOld As String, applicationType As String)
Dim objectApplication As Object
Dim documentApplication As Object
On Error Resume Next
Set objectApplication = GetObject(, applicationType)
On Error GoTo 0
If objectApplication Is Nothing Then
Set objectApplication = CreateObject(applicationType)
End If
objectApplication.Visible = True
On Error Resume Next
Set documentApplication = objectApplication.Workbooks(FileHandling.GetFilenameFromPath(fileNameOld)) 'Excel
Set documentApplication = objectApplication.Documents(FileHandling.GetFilenameFromPath(fileNameOld)) 'Word
Set documentApplication = objectApplication.WorkSheets(FileHandling.GetFilenameFromPath(fileNameOld)) 'Mathcad
Set documentApplication = objectApplication.Presentations(FileHandling.GetFilenameFromPath(fileNameOld)) 'PowerPoint
Set documentApplication = objectApplication.Projects(FileHandling.GetFilenameFromPath(fileNameOld)) 'MS Project "Msproject.Application"
Set documentApplication = objectApplication.Documents(FileHandling.GetFilenameFromPath(fileNameOld)) 'MS Visio "Visio.Application"
If documentApplication Is Nothing Then
Set documentApplication = objectApplication.FileOpen(fileNameOld) ' add read only
End If
documentApplication.SaveAs filename:=filenameNew
Set objectApplication = Nothing
Set documentApplication = Nothing
End Sub
What is a possible solution to handle all vba acceptable document types?
You can use GetObject("Filename") to open a file directly in its application. So something like this can open any file that has its extension in the Windows Registry. That will be most file types; certainly the Office applications. Whether you'll be able to use SaveAs will depend on whether those applications support OLE Server (meaning they have a coding interface exposed). Again, all the Office applications do support this.
You'll probably want to put in some error-handling for the case the application for the file extension can't be found in the Registry. And of course in case the file name doesn't exist.
My example is for Excel and Word, only - you should be able to fill in others. My code makes sure the file is visible and available to the user as that makes it easier to trouble-shoot. You can, of course, change that once you have everything working satisfactorily.
Sub OpenFileInUnknownApp()
Dim objFile As Object
Dim objApp As Object
Dim sPath As String, sExt As String
Dim sFileName As String
Dim sAppName As String
Dim snewfilename As String
sPath = "C:\Test\"
sFileName = sPath & "Quote.docx" 'RngNames.xlsx"
snewfilename = sPath & "NewName"
'''Open the file in its application
Set objFile = GetObject(sFileName)
Set objApp = objFile.Application
sAppName = objApp.Name
Select Case sAppName
Case Is = "Microsoft Excel"
Dim wb As Excel.Workbook
sExt = "xlsx"
objApp.Visible = True
Set wb = objFile
wb.Activate
wb.Windows(1).Visible = True
objApp.UserControl = True 'so that it "lives" after the code ends
objApp.Activate
wb.SaveAs "sNewFileName" & sExt
Case Is = "Microsoft Word"
Dim doc As word.Document
sExt = "docx"
objApp.Visible = True
Set doc = objFile
objApp.Activate
doc.SaveAs2 "sNewFileName" & sExt
Case Else
End Select
Set objFile = Nothing
Set objApp = Nothing
End Sub

How to name a new Excel workbook automatically in VBA

I would like to create a New workbook and name it as today's date and DE.
(Eg : 22.01.2018-DE)
Format(Date, "dd/mm/yyyy") & "-DE"
If the workbook is already existed or opened, then delete it or close it. Finally save the workbook. I used the code below but not working. Displaying object defined error. Help me
I need to rename Land-DE to 22.01.2018-DE.
Sub createlandDE()
Dim wb As Workbook
Set wb = Workbooks.add
ActiveWorkbook.Names.add Name:=Format(Date, "dd/mm/yyyy") & "-DE"
Dim path As String
Dim FSO As Object
path = "Q:\Job\Land-DE.xlsx" 'Need to rename the file here
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(path) Then
On Error Resume Next
Workbooks("Land-DE").Close False 'Workbook name must automatically come here
Kill path
wb.SaveAs path
Else
wb.SaveAs path
End If
How about this:
Sub createlandDE()
Dim wb As Workbook
Set wb = Workbooks.Add
NameValue = Format(Date, "dd-mm-yyyy") & "-DE"
Dim path As String
Dim FSO As Object
delpath = "Q:\Job\Land-DE.xlsx" 'Need to name the file to delete
path = "Q:\Job\" & NameValue & ".xlsx" 'Need to rename the file here
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(path) Then
On Error Resume Next
Workbooks(NameValue).Close False
Kill delpath
wb.SaveAs path
Else
wb.SaveAs path
End If
End Sub
Try with saving as:
Workbooks("Land-DE").SaveAs Filename:="Q:\Job\22.01.2018.xlsx"
Then delete the file with the old name.
To make it look better, consider saving "Q:\Job\22.01.2018.xlsx" as a String variable.
I believe you are editing the wrong property.
I would simply use ActiveWorkbook.Name = [your desired name]

Using VBA to unzip file without prompting me once (choose "Yes to All" for any dialog box)

There is an unzipping code I'd like to adjust 4 my needs.
Sub Unzip()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefinePath As String
' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"
If Fname = False Then
'Do nothing
Else
'Destination folder
DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\" ' Change to your path / variable
If Right(DefinePath, 1) <> "\" Then
DefinePath = DefinePath & "\"
End If
FileNameFolder = DefinePath
' Delete all the files in the folder DefPath first if you want.
' On Error Resume Next
' Kill DefPath & "*.*"
' On Error GoTo 0
'Extract the files into the Destination folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
' MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
Somewhere here:
`Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere`
a dialog box appears asking me if I want to overwrite the file that have the same names - and Yes I do want to overwrite them, but without answering the dialog box - I would like to hardcode it into the code, please.
I've found this page https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx but I just don't know how to add this parameter #16 which is "Respond with "Yes to All" for any dialog box that is displayed."
Can U help me with that?
And the last thing:
can You explain oApp.Namespace(Fname).items line for me.
I've really tried to guess it myself, but I thing I'm to short 4 this.
the code that results in no questions or no prompting of any kind is as follows:
Option Explicit
Sub Bossa_Unzip()
Dim FSO As Object
Dim oApp As Object ' oApp is the object which has the methods you're using in your code to unzip the zip file:
'you need to create that object before you can use it.
Dim Fname As Variant
Dim FileNameFolder As Variant ' previously Dim FileNameFolder As Variant
Dim DefinePath As String
' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"
If Fname = False Then
'Do nothing
Else
'Destination folder
DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\" ' Change to your path / variable
If Right(DefinePath, 1) <> "\" Then
DefinePath = DefinePath & "\"
End If
FileNameFolder = DefinePath
' Delete all the files in the folder DefPath first if you want.
' On Error Resume Next
' Kill DefPath & "*.*"
' On Error GoTo 0
'Extract the files into the Destination folder
Set oApp = CreateObject("Shell.Application") ' you need to create oApp object before you can use it.
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items, 16
'MsgBox "You'll find the files here: " & DefinePath
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
Of course this site helped me a lot - its CpyHere explanation site.
One thing I don't understand is why Fname and FileNumberFolder need to be declared as variant. In my opinion, they should be declared as String. Just look at this screenshot.
But when I declare them that way, the code gives me error.
Just look here, when the variables already have their values (first picture). The FileNameVariable and DefinePath variable have the exact same value, and it looks like a string 4 me. How is that necessary, that I need to declare another variable - FileNameVariable in that case (in 17th line) with the same value, but variant type.
please explain that to me, someone.

Creating and saving Excel document From VBA in Word

I want to be able to run a macro in a Word document that will create an Excel document and then save that spreadsheet in a shared folder.
This is the code I have so far:
Public Sub Monthly_Commission_Extract()
Dim objExcel
Dim objDoc
Dim objSelection
Dim SaveAs1 As String
SaveAs1 = ("\\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
Set objExcel = CreateObject("Excel.Application")
Set objDoc = objExcel.Workbooks.Add
objExcel.Visible = True
Set objSelection = objExcel.Selection
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
The code is giving me an error:
Run-time error '424': Object required
At the following piece of code:
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=xlText, CreateBackup:=False
Please advise how I get around this.
objExcel.ActiveWorkbook.SaveAs
not just
ActiveWorkbook.SaveAs
Anything which "belongs" to Excel must be prefixed with your objExcel application reference.
Below is a simple and straight forward code that creates a new excel workbook and saves it into a path on your local disk. This VBA code has ben tested from inside MS Word.
Private Sub CreateExcel()
Dim myExcel As Object
Dim myWb As Object
Set myExcel = CreateObject("Excel.Application")
Set myWb = myExcel.Workbooks.Add
Application.DisplayAlerts = False
myWb.SaveAs FileName:="D:\test\dump.xls"
Application.DisplayAlerts = True
myWb.Close False
Set myWb = Nothing
myExcel.Quit
Set myExcel = Nothing
End Sub
In your case, the following would have worked because 'objDoc' is derived from the excel object reference.
objDoc.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Oh captain, yes my captain,
the errormessage says clearly that a object is missed, I think this line
SaveAs1 = ("\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
is the problem You should a SET-Statement out of this, by starting this line with "SET ", then you have the object required.