Access VBA opening Temp.xls instead of set filepath - excel

I have code in Access that opens an excel template then saves it based on filepath. The template is then closed and I have put code in that will open the recently saved file. However, the file that opens is the temp.xlsm.
I have spent hours trying to figure out where I am going wrong but no luck, unless I am asking google the wrong question.
This is the part of my code that opens the template, saves it as, and then closes the template to reopen the saved file. Debugs are giving the correct file paths so I can't understand why the temp file keeps opening.
Dim objXLApp As Object
Dim objXLBook As Object
Dim objXLBookNew As Object
Dim FilePath As String
Dim strPath As String
Set objXLApp = CreateObject("Excel.Application")
FilePath = Forms!fm_MainMenu!fm_FilePath_Template.Form!File_Path & "\" & Forms!fm_MainMenu!fm_FilePath_Template.Form!File_Name & "." & Forms!fm_MainMenu!fm_FilePath_Template.Form!File_Type
Debug.Print FilePath
Set objXLBook = objXLApp.Workbooks.Open(FilePath)
objXLApp.Application.Visible = True
Maxletter = DMax("LetterID", "tbl_ReportNo", "[JobNo]= '" & [Forms]![fm_JobHeader]![Job_No] & "'")
Me.ReportNo = DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter)
objXLBook.ActiveSheet.Range("AI13") = [Forms]![fm_JobHeader]![Job_No] & DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter)
objXLBook.ActiveSheet.Range("N15") = [Forms]![fm_JobHeader]![Client].Column(1)
objXLBook.ActiveSheet.Range("AF14") = [Forms]![fm_JobHeader]![PONo]
objXLBook.ActiveSheet.Range("S17") = [Forms]![fm_JobHeader]![JobDescription]
objXLBook.ActiveSheet.Range("AT15") = Now()
objXLBook.ActiveSheet.Range("T13") = Me.Discipline.Column(1)
objXLBook.ActiveSheet.Range("Z13") = Me.Type.Column(1)
objXLBook.ActiveSheet.Range("AT16") = Me.RequestWONo
objXLBook.ActiveSheet.Range("S19") = Me.SiteLocation.Column(1)
Dim path_ As String
path_ = Forms!fm_MainMenu!fm_FilePath_Report.Form!File_Path & "\" & [Forms]![fm_JobHeader]![Job_No] & DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter)
Dim name_ As String
name_ = [Forms]![fm_JobHeader]![Job_No] & DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter) & ".xlsm"
Debug.Print path_
Debug.Print name_
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(path_) Then .CreateFolder path_
End With
objXLBook.SaveCopyAs FileName:=path_ & "\" & name_
objXLBook.Close False
Set objXLBook = Nothing
Dim path2_ As String
path2_ = Forms!fm_MainMenu!fm_FilePath_Report.Form!File_Path & "\" & [Forms]![fm_JobHeader]![Job_No] & DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter)
Dim name2_ As String
name2_ = [Forms]![fm_JobHeader]![Job_No] & DLookup("Letter", "tbl_LetterID", "Letter_ID = " & Maxletter) & ".xlsm"
Set objXLApp = CreateObject("Excel.Application")
Set objXLBookNew = objXLApp.Workbooks.Open(path2_ & "\" & name2_)
Debug.Print path2_
Debug.Print name2_
objXLApp.Application.Visible = True
DoCmd.Hourglass False ' turn off hourglass
Set objXLBookNew = Nothing
Set db = Nothing
Set rec = Nothing
Debug of file_ C:\Users\OneDrive\Current Working Docs\Reports Database\ABC123AY
Debug of path_ ABC123AY.xlsm
Debug of file2_ C:\Users\OneDrive\Current Working Docs\Reports Database\ABC123AY
Debug of path2_ ABC123AY.xlsm
But file that is being opened is
C:\Temp\Temp.xlsm
Maybe I have been looking at this too long and the obvious is staring me in the face but I am gaining frustration. Any help very much appreciated.

Related

excel vba domdocument parsing xml from TNT tracking system: in some pcs object load return no document

I have a function to parse an xml document received from the tracking system of TNT courier,
this is example of a query url i'm using:
https://www.tnt.it/tracking/getXMLTrack?WT=1&ConsigNos=RL38536236
the function worked correctly on all PCs until yesterday,
when on some PCs the method .Load(URL) of DOMDocument object returns false result and the DocumentElement property is null,
the thing is: if i browse to that url (i used firefox, chrome, edge, iexplore)
the xml is showed correctly!
this is the code:
Function TrackTNTlist(LDV As String) As Collection
Dim TNTlist As New Collection
Dim Obj As MSXML2.DOMDocument60
Dim Verifica As Boolean
Dim XMLTNT As String
Dim NodoLista As IXMLDOMNodeList
Dim NodoSingolo As IXMLDOMNode
Dim Nome As IXMLDOMNode
Dim DataConsegna As IXMLDOMNode
Dim NomeRicevente As IXMLDOMNode
Dim Destinatario As IXMLDOMNode
Dim ConsignmentDetails As IXMLDOMNode
Dim DataPrevConsegna As IXMLDOMNode
Dim NuovaLDV As IXMLDOMNode
Dim Dest As String, DatiSped As String
On Error GoTo RigaErrore
XMLTNT = "https://www.tnt.it/tracking/getXMLTrack?WT=1&ConsigNos=" & LDV
Set Obj = New MSXML2.DOMDocument60
Obj.async = False
Verifica = Obj.Load(XMLTNT)
If Verifica = True Then
MsgBox "File XML " & XMLTNT & "loaded"
Else
MsgBox "File XML NOT loaded"
TNTlist.Add "ERROR - XML tracking data not loaded"
Exit Function
End If
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
If NodoSingolo Is Nothing Then
TNTlist.Add "LDV non trovata"
Else
Set NodoList = Obj.DocumentElement.SelectNodes("Consignment/StatusDetails")
Set ConsignmentDetails = Obj.DocumentElement.SelectSingleNode("Consignment/ConsignmentDetails")
DatiSped = ""
DatiSped = "LETTERA DI VETTURA: " & LDV & Chr(10)
If Not ConsignmentDetails Is Nothing Then
DatiSped = DatiSped & "RIF. MITTENTE: " & ConsignmentDetails.ChildNodes(0).Text & Chr(10)
DatiSped = DatiSped & "TIPO SERVIZIO: " & ConsignmentDetails.ChildNodes(1).Text & Chr(10)
DatiSped = DatiSped & "NUM. COLLI: " & ConsignmentDetails.ChildNodes(3).Text & Chr(10)
End If
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
Dest = ""
Set DataConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DeliveryDate")
Set NomeRicevente = Obj.DocumentElement.SelectSingleNode("Consignment/CollectionName")
Set Destinatario = Obj.DocumentElement.SelectSingleNode("Consignment/ReceiverDetails")
Set DataPrevConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DueDate")
Set NuovaLDV = Obj.DocumentElement.SelectSingleNode("Consignment/HeldInDepotDetails/HID1ReplacingDoc")
If NodoSingolo.Text = "Spedizione consegnata" Then
Dest = "CONSEGNATA A: " & Chr(13)
Else
Dest = "PREVISTA CONSEGNA A: " & Chr(10)
End If
If Not Destinatario Is Nothing Then
Dest = Dest & Destinatario.ChildNodes(4).Text
Dest = Dest & " (" & Destinatario.ChildNodes(6).Text & ")" & Chr(10)
End If
If Not DataPrevConsegna Is Nothing Then
Dest = Dest & DataPrevConsegna.ChildNodes(0).Text & Chr(10)
End If
If Not DataConsegna Is Nothing Then
Dest = Dest & "Data consegna: " & DataConsegna.Text & Chr(10)
End If
If Not NomeRicevente Is Nothing Then
Dest = Dest & "Ha ritirato: " & NomeRicevente.Text & Chr(10)
End If
If Not NuovaLDV Is Nothing Then
Dest = Dest & "NUOVA LETTERA DI VETTURA: " & NuovaLDV.Text & Chr(10)
End If
Dest = Dest & "Dettaglio tracking:" & Chr(10)
TNTlist.Add DatiSped & Chr(10) & Dest & Chr(10)
For Each Nome In NodoList
TNTlist.Add Nome.ChildNodes(1).Text
TNTlist.Add Nome.ChildNodes(2).Text
Next
End If
salto = 1
If salto <> 1 Then
Set NodoSingolo = Obj.DocumentElement.SelectSingleNode("Consignment/StatusDetails/StatusDescription")
If NodoSingolo Is Nothing Then
TNTlist.Add "LDV non trovata"
Else
If NodoSingolo.Text = "Spedizione consegnata" Then
Set DataConsegna = Obj.DocumentElement.SelectSingleNode("Consignment/DeliveryDate")
Set NomeRicevente = Obj.DocumentElement.SelectSingleNode("Consignment/CollectionName")
Set Destinatario = Obj.DocumentElement.SelectSingleNode("Consignment/ReceiverDetails")
Dest = Destinatario.ChildNodes(4).Text
Dest = Dest & " (" & Destinatario.ChildNodes(5).Text & ")"
TNTlist.Add NodoSingolo.Text & " : " & Dest & " - " & NomeRicevente.Text & " - " & DataConsegna.Text
TNTlist.Add DataConsegna.Text
End If
End If
End If
Set TrackTNTlist = TNTlist
Exit Function
RigaErrore:
MsgBox Err.Number & vbNewLine & Err.Description
Application.EnableEvents = True
Resume Next
End Function
the problem occurs only in few pcs,
they have the same system configuration,
below two screen shots, one from a pc where the function work correctly ad one from another where the problem occurs.
debug screenshot of correct execution
debug screenshot of error execution
in both pcs browsing to the url show the xml correctly.
Could anyone help me to understand what might cause the problem?
Thanks a lot!
Francesco

Excel VBA - Save As suggested filename and filepath from a cell value

I have a macro in an Excel Workbook, that is connected to a button that says Export
When I click the button, it triggers the Export XML dialog and I have to manually search for a folder to export it into and enter the filename.
Since the folders in my Documents are named exactly the same as the value of the Cell A24, i would like it to direct itself into the correct folder and suggest me a filename based on the value of the Cell A24 with some extra text behind it.
So far i have this in the VBA:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim POFileName As String
Dim FOFileName As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24")
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22")
POFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath & FOFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath & POFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
This gives me the right filename suggestion, but it doesn't direct me to the folder and goes to Desktop.
Any help would be appriciated!
EDIT:
I tried merging the Strings together a bit more and came up with this:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22") & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
The problem is, that VBA thinks that in:
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
the first Range("A24") belongs to the filename part and doesn't continue on with the filepath. So if the value in A24 was "test", then this suggests saving the xml to Desktop with the filename testttest_report 11 2020

Error System.Runtime.InteropServices.COMException: Code creates some PDFs with ExportAsFixedFormat but then errors out

My VB.Net program in Visual Studio creates Excel files and then saves them as PDF but after so many(30, 40 or whatever, not the point) it errors out saying "Error System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'".
Probably I am thinking it is the way Excel gets closed/released?
The error is from this line of code after I open an Excel document and try to save it as PDF. Again, that always happens after some documents have been already saved as PDF(sometimes 30, sometimes 50...):
xwb.ActiveSheet.ExportAsFixedFormat(0, "\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesPDF\" & originalCustomerName & " " & customerNumber & " " & todaysDate & ".pdf")
Here is the whole code I have:
THIS CREATES THE EXCEL DOCUMENT AND FILLS IT WITH DATA:
Public Sub PopulateSheet(ByVal dt As Data.DataTable, ByVal File As String)
Dim oXL As Excel.Application = CType(CreateObject("Excel.Application"), Excel.Application)
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
oWB = oXL.Workbooks.Add
oSheet = CType(oWB.ActiveSheet, Excel.Worksheet)
'****Spreadsheet gets populated
......
'****Then
oWB.SaveAs(File)
oRng = Nothing
oXL.Quit()
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(oXL)
Marshal.FinalReleaseComObject(oSheet)
Marshal.FinalReleaseComObject(oWB)
oSheet = Nothing
oWB = Nothing
oXL = Nothing
FINALLY THIS SAVES THE DOCUMENT AS PDF:
Dim xl As Object
Dim xwb As Object
xl = CreateObject("Excel.Application")
dt = CreateTable()
PopulateSheet(dt, "\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesExcel\" & originalCustomerName & " " & customerNumber & " " & todaysDate & ".xlsx")
'****Open xlsx doc to save as pdf
xwb = xl.Workbooks.Open("\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesExcel\" & originalCustomerName & " " & customerNumber & " " & todaysDate & ".xlsx")
xwb.ActiveSheet.PageSetup.Zoom = False
xwb.ActiveSheet.PageSetup.FitToPagesWide = 1
xwb.ActiveSheet.PageSetup.FitToPagesTall = False
'****Save as pdf
xwb.ActiveSheet.ExportAsFixedFormat(0, "\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesPDF\" & originalCustomerName & " " & customerNumber & " " & todaysDate & ".pdf")
xl.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xl)
xl = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(xwb)
xwb = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
Any help highly appreciated. Thank you
********COMMENT:** I feel there is a problem with how Excel gets released/closed at the end of the two Excel processes. I thought that because the program runs fine and saves the Excel files as PDF, but every time it never creates all the files. It stops after a number of PDF files get created at the line where there is "ExportAsFixedFormat". It never stops at the same specific file, so I would say there isn't a problem with any specific PDF.
I mainly changed "ExportAsFixedFormat" with "Printout" and now it seems to be working fine. Thanks to all for your help!
THIS IS THE CODE i HAVE NOW:
Dim Path As String = "\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesExcel\" & originalCustomerName & " " & customerNumber & " 050720.xlsx"
Dim Excel As Excel.Application = New Excel.Application
Dim WorkBook As Excel.Workbook = Excel.Workbooks.Open(Path)
Dim WorkSheets As Excel.Sheets = WorkBook.Sheets
Dim WorkSheet As Excel.Worksheet = CType(WorkSheets(1), Microsoft.Office.Interop.Excel.Worksheet)
Excel.DisplayAlerts = False
Excel.Visible = False
'SAVE AS PDF
Dim totalFileName As String = "\\ken-resourcesan\fileshares\fieldshare\IT\nsantagata\ARStatements_CustomerInvoicesPDF\" & originalCustomerName & " " & customerNumber & " " & todaysDate & ".pdf"
Excel.ActiveSheet.Printout(Copies:=1, Preview:=False, ActivePrinter:="Microsoft Print to PDF", PrintToFile:=True, Collate:=True, PrToFileName:=totalFileName, IgnorePrintAreas:=False)

How to fix "Bad File Name or Number" error when saving an Excel file via macro?

I need to save my excel file using a macro and I am making use of an old macro I made a while ago - which worked just fine. But now, I am getting an error which I don't seem to understand all to well.
Code:
Option Explicit
Sub SaveFile()
Dim strDir As String, saveDate As String, userMachine As String, Filename As String, yearDate As String, monthDate As String, filePath As String
Dim ws1 As Workbook
Set ws1 = Workbooks("Template.xlsm")
Application.DisplayAlerts = False
saveDate = "01/02/2019"
yearDate = Year(saveDate)
monthDate = Format(saveDate, "MMMM")
saveDate = Format(saveDate, "dd-mm-yyyy")
userMachine = "User - 12345"
strDir = "C:\user12345\desktop\Final Results\" & yearDate & "\" & monthDate & "\" & Format(saveDate, "dd-mm-yyyy") & "\"
filePath = ""
Filename = userMachine & " - " & saveDate & ".xlsx"
filePath = Dir(strDir & Filename)
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
Else
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
End If
End Sub
The error is on this line filePath = Dir(strDir & Filename) and the error is:
Bad File Name or Number
As far as I can see, my name for the file meets the requirements to save it so I am at a total loss here.
The original code I had was this:
strDir = "C:\username\desktop\" & Format(DateAdd("d", -1, Date), "dd_mm_YY") & "\"
FilePath = Dir(strDir & "myFile.xlsx")
Bad File Name or Number means that the string you are using to save the file is not valid.
You could replace the hardcoded string to your desktop with a relative reference from a function, such as:
Function getDeskTopPath() As String
'Get Desktop path as string
'Command can be exchanged for other information... see list below
'AllUsersDesktop
'AllUsersStartMenu
'AllUsersPrograms
'AllUsersStartup
'Desktop
'Favorites
'Fonts
'MyDocuments
'NetHood
'PrintHood
'Programs
'Recent
'SendTo
'StartMenu
'Startup
'Templates
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
getDeskTopPath = oShell.SpecialFolders("Desktop")
Set oShell = Nothing
End Function

Vbscript to move an excel column to a new excel file

I got a good part a script and from here I do not know where to start.
In the script below I open a file move the columns and save the file in a new folder with date and time in front of it.
What I would like to do is copy those columns to a new File
I do not mind changing the way this script goes I can change it completly
Set objArgs = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
For I = 0 to objArgs.Count - 1
CmplName = Year(Now()) & Month(Now()) & Day(Now()) & "H" & Hour(Now()) & "_"
FullName = objArgs(I)
FileName = Left(objArgs(I), InstrRev(objArgs(I), ".") )
RdyPath = "OrReady"
FNPathLen = InstrRev(FullName, "\")
FNLen = Len(FullName)
SNLen = FNLen-FNPathLen
ShortFullName = Right(FullName, SNLen)
ShortFileName = Left(ShortFullName, InstrRev(ShortFullName, ".") )
AdSavPath = Left(FullName, FNPathLen) & RdyPath & "\"
If fso.FolderExists(AdSavPath) Then
Else
fso.CreateFolder(AdSavPath)
End If
Set objExcel = CreateObject("Excel.application")
set objExcelBook = objExcel.Workbooks.Open(FullName)
objExcel.application.visible=false
objExcel.application.displayalerts=false
Set Cols = objExcel.Range("C1","C100000")
Set TCols = objExcel.Range("R1","R100000")
Cols.Cut
TCols.Insert
Set Cols = objExcel.Range("B1","B100000")
Set TCols = objExcel.Range("F1","F100000")
Cols.Cut
TCols.Insert
NewFile = AdSavPath & CmplName & ShortFileName & "xlsx"
objExcel.Workbooks(ShortFullName).SaveAs _
AdSavPath & CmplName & ShortFileName & "xlsx", 51
objExcel.Application.Quit
objExcel.Quit
Set objExcel = Nothing
set objExcelBook = Nothing
If fso.FileExists(NewFile) Then
MsgBox NewFile & " Exist Original File will be deleted => " & FullName
fso.DeleteFile(FullName)
Else
MsgBox " File Was Not Created "& NewFile & " (Did not Exist) Did not Delete Original File"
End If
Next

Resources