Excel VBA - URLDownloadToFile - Data missing in downloaded file - excel

I am using the below code to download an excel file from a url. The URL (which I can not share here) is for a ticketing system. I used the search button in the website to get all open and in progress tickets. After that there is a Export drop down button and from the drop down I selected Excel. The url I used is the code is the url of this Export to Excel button.
The code is exporting the excel file to given path, but there is only the page header and footer data to show the time of download and two lines saying "Displaying 0 issues at 07/Jul/14 3:14 PM." and "No Issues Found". in the file.
If I use the url directly on any website, it opens the file with data. If I use Workbooks.open "myUrl" same blank file is opening.
Can anyone please check what is wrong?
Sub downloadFile()
Test = Dir("C:\Users\" & Environ("username") & "\" & "SearchResult.xls")
If Not Test = "" Then
Kill ("C:\Users\" & Environ("username") & "\" & "SearchResult.xls")
End If
mylink = ""
myresult = 0
mylink = "http://mylink.com/issueviews:SearchResult-excel-all-fields/temp/SearchResult.xls?jqlQuery=status+in+%28Open%2C+%22In+Progress%22%29&tempMax=1000"
myresult = URLDownloadToFile(0, mylink, "C:\Users\" & Environ("username") & "\" & "SearchResult.xls", 0, 0)
If myresult <> 0 Then
MsgBox "Error downloading " & mylink & Chr(10) & Error(myresult)
Else
MsgBox "File has been downloaded"
End If
End Sub

There is not enough information available from the data you have provided.
Basically there is some difference between what happens (on the HTTP protocol query/response level) when you use IE manually and when you run the code.
Typical things are redirecting status codes (see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection) and missing authentication headers (see http://en.wikipedia.org/wiki/HTTP_header)
If you can not install tools (e.g. cURL) it will be difficult to guess as I don't know what kind of tools you have available.
There are some network diagnostics tools built right into web browsers (in Internet Explorer press F12, in Google Chrome press Ctrl+Shift+I)
(EDIT after comments) You can find what is the exact sequence of http requestes/responses exchanged between the web browser and the web server using the network tab in the browser's built-in developer tools.
Usage instructions for Google Chrome are at https://developer.chrome.com/devtools/docs/network#network-resource-details
Usage instructions for Internet Explorer are at http://msdn.microsoft.com/en-us/library/ie/dn255004(v=vs.85).aspx
Once you'll know what is the right sequence of messages try to reproduce it using cURL.
Once you succeed you can try to reproduce the sequence using Excel VBA functions with similar meaning or you can just call cURL command line tool from Excel as described here: Execute a command in command prompt using excel VBA (or in some of its linked or related questions)

Related

Saving Excel Files to Sharepoint using VBA

I am attempting to run a query in Excel and update the data to Sharepoint (accessible via Teams) on a set schedule.
Desired folder destination:
https://rxsafeway.sharepoint.com/:f:/r/sites/EXELiveProductionTool/Shared%20Documents/General/Portland/Individual%20Performance%20Update?csf=1&web=1&e=oFwj6i
VBA code used:
ThisWorkbook.SaveAs Filename:="https://rxsafeway.sharepoint.com/sites/EXELiveProductionTool/Shared%20Documents/General/Portland/Individual%20Performance%20Update/" & ".xlsm"
Details:
-The above VBA code has been used successfully while connected to VPN and on the company network.
-It works inconsistently... Potentially an upload limit?
-Notice that the "/:f:/r/" has been removed, a "/" has been added after "Update", and everything passed "Update" has been removed in the working code
Question:
Sometimes the code works and sometimes I get a Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed
Is there a syntax error, or a smarter way to save the file?
You probably getting this error due to the MAX_PATH 256 limitation.
Your filename is too long and therefore will have a longer Windows path as well.
I suggest you to view your SharePoint files in File Explorer (see the documentation here). By doing so, every file/folder in your sharepoint will have a normal path and you'll not have anymore to use your file's url.
After that, you can use this formula to save your xlsm in some location in sharepoint :
Path="C:\Users\AKow\Sharepoint_Name\Path_to_your_file"
Filename = "Individual Performance Update"
ThisWorkbook.SaveAs Filename:= Path & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled

custom function in excel using vba that works in any matchine

I have created a custom function via vba in excel. If I use it in my computer, it works ok, but if I change the file to another computer (where this computer also has the created function), it does not work. I must change the path of the created function. Is there any way to not change the path everytime I copy the file into another computer?
='C:\Users\Usuario1\Documents\Complementos\BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!asbusinessday('C:\Users\Usuario1\Documents\Complementos\AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Solution 1: You could use a common paths in both computers
(for example: C:\work , C:\Work2)
Solution 2: You could put all files in the same path (C:\work), then you only need the to put the file name
='BondsTIRMDuration.xlam'!TIrbonds($A2;F2;'AsBusinessDay.xlam'!asbusinessday('AsBusinessDay.xlam'!PrevBusinessDay(HOY())))*100
Just save your add-in in the correct path on every computer.
It should be something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\AddIns\
See Install and Use Excel Add-ins to determine the correct path.
If your add-in is installed correctly you should be able to run your user defined function without a path.
You can call special folder with application.
MsgBox Application.DefaultFilePath
This example will be: C:\Users\Usuario1\Documents
'Here are a few VBA path functions
MsgBox Application.Path
MsgBox Application.DefaultFilePath
MsgBox Application.TemplatesPath
MsgBox Application.StartupPath
MsgBox Application.UserLibraryPath
MsgBox Application.LibraryPath
You can too create wscrit object to call another paths, for example:
MsgBox CreateObject("Wscript.Shell").SpecialFolders("Desktop")
Example folders for Wscript.shell object:
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates
And execute a macro like this,(allways have to use same directory):
Sub Macro()
AddIns.Add Filename:=Application.DefaultFilePath & "\Complement.xlam"
AddIns("Complement").Installed = True
End Sub

How to discover Oleobject ClassType of files?

I'm stuck how to determine files' Classtypes needed to use in code to embed these files into a Word document:
Selection.InlineShapes.AddOLEObject ClassType:="AcroExch.Document.11", _
FileName:="C:\Work\Dashbaord & ".pdf", LinkToFile:=False, _
DisplayAsIcon:=False
I need to embed csv, pdf, xlsx and txt files. How I can automatically loop all files in folders and automatically determine the ClassType of each?
In order to insert a file as an OLE Object the file type needs to have an available OLE Server installed on the machine, or it needs to be in a format that the Windows Packager mechanism can "wrap up" into an OLE type. Before you go this route you need to ensure that anyone who tries to work with such a document has corresponding OLE Server software installed on the machine on which the document is opened. Just because the machine that creates an embedded OLE object can do so doesn't mean another machine can work with the result, later on.
OLE Server software will be noted in the Registry. The Microsoft Office applications (Word, Excel, PowerPoint, etc.) are able to function as OLE Servers. In the Registry you'll find corresponding entries such as Word.Document and Excel.Workbook... or AcroExch.Document for PDF files if Microsoft Office and the Adobe Acrobat Reader are installed.
One way to figure out which ClassTypes to use would be to manually insert each file type and inspect the resulting Embed field code.
To look the ClassTypes up in the Registry, something like the following code sample can be used in Word. Word has the function System.PrivateProfileString that wraps up a Windows API call to the Registry. It can be used to retrieve and to write information. (This code does not loop the files in a directory as the question was about how to determine the ClassType. For the sake of simplicity a file extension is hard-coded.)
A file type that does not have an OLE Server won't have a . in the default value of the Registry key. A .txt file, for example, is listed as txtfile. You may have to watch out for some file types; for example on my installation a csv file is listed as Excel.CSV, which may not be what you want...
Sub RetrieveOLEInfo()
Dim fileExt As String
Dim regKey As String
Dim oleServer As String
fileExt = "docx"
regKey = "HKEY_Classes_Root\."
oleServer = System.PrivateProfileString("", regKey & fileExt, "")
'Debug.Print oleServer
If InStr(oleServer, ".") = 0 Then
Debug.Print "Insert as a Package"
Else
Debug.Print "Insert as: " & oleServer
End If
End Sub

ExportAsFixedFormat fails sometimes

I have a spreadsheet with forms and macros that worked until recently. The first time I saw the described behavior was the first time I tried using this particular function in Excel 2016 (Windows 10), though I'm not sure that's the cause.
The issue I'm having is with the following line
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Which comes from the following macro:
Sub PDFLabelsSheet()
'On Error GoTo errHandler
'enter name and select folder for file
strFile = "Labels_PrintGroup-" & lstPrintGroup.Value _
& "_" _
& Format(Now(), "yyyy-mm-dd\_hhmm") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
Worksheets("Label Template - 100X150").Visible = True
UnprotectTab "Label Template - 100X150"
pdfFilePath = Application.GetSaveAsFilename(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If pdfFilePath <> "False" Then
Worksheets("Label Template - 100X150").Select
Worksheets("Label Template - 100X150").Range("A1").Select
Worksheets("Label Template - 100X150").Range("A1").Activate
Cells.Activate
Worksheets("Label Template - 100X150").PageSetup.FirstPageNumber = 1
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
exitHandler:
ExecutionEnd
Exit Sub
errHandler:
MsgBox "Something went wrong, a PDF could not be created", vbCritical
Resume exitHandler
End Sub
I've tried permutations of the ExportAsFixedFormat function, changing it to Worksheets("name"), (number), ActiveSheet.... etc.
Prior to executing this particular Sub, the worksheet is unhidden and unprotected. I've tried setting the entire range as PrintArea, I've tried selecting and activating the range to be exported as well.
The most frustrating part is it works sometimes. I've gone as far as putting in code that spits out every property of the PageSetup collection to make sure that something is not blowing things up since the output depends so strictly on the page setup.
When I navigate to this worksheet manually and choose the export function from the file menu, I get the same error. If I click around in that worksheet for a bit the Export function as well as the Macro work.
The PDFLabelSheets Sub does get called from another Sub (invoked by a form's button press) which compiles a boatload of data into this tab, though I've ruled it out as the culprit as successive runs of just the PDF code will succeed then fail without running the other code.
I’ve recently solved a problem that was similar in the following ways:
It involved the failure of the ExportAsFixedFormat, Type:=xlTypePDF
statement
The statement failed with no error message; it simply
stopped the execution of the VBA code
The failure was inconsistent,
and the conditions for failure or success were not obvious
Below is a summary of how I solved it; perhaps this will suggest some useful approaches you can use.
My Excel VBA code was running under Windows 7 as an unattended, end-of-day scheduled task in the background, usually when no one was logged in. Most of the time the code would work, but sometimes it would not. I could not capture the screen after a crash, and capturing the various window contents did not help: there was no useful diagnostic text. I finally tried logging program execution milestones to a disk file, reopening and closing the file for each milestone, so no text would be lost if the program subsequently crashed. That isolated the problem to the ExportAsFixedFormat statement but did not diagnose the problem.
I finally tried having the VBA code save a copy of the workbook just prior to the point of failure. I was hoping that, on re-opening the copy, I’d be able to see what was wrong. That did not help. However, I did notice something strange when comparing the .xlsm files saved on successful and unsuccessful executions – the former were just a little larger.
Digging into the .xlsm files (which are really .zip files), I noticed that, in the xl\printerSettings subfolder, the printerSettings1.bin file was larger after successful runs. Using the SysInternals Strings utility to inspect the .bin files, I found that, in the unsuccessful runs, this file contained only the name of the default printer on the home computer where I had developed the application, which was not the office computer where it was executing. On the successful runs, the .bin file also contained the name of the default printer in the office.
This was the critical difference. In that office, the main computer executes the Excel program shortly after the end of the working day. Ordinarily, during the day this computer prints to a laser printer (set as the default printer) attached to another computer on the network, and that other computer is turned off at the end of the working day. Therefore, depending on accidents of timing, sometimes the end-of-day Excel program would see a valid, available default printer, sometimes not.
Some Excel commands, including the command to save as a .pdf, work properly only when the active printer is valid. There is a similar observation at can't set PageSetup.Orientation = xlLandscape from MS Project, concerning assignments to the fields of .PageSetup. In my case, failing to work properly meant crashing without generating any error message.
I later discovered that my problem was not simply the unavailability of the default laser printer over the network; it was also caused by something irregular about the printer definition. I had added code to log the VBA property Application.ActivePrinter; just prior to a crash, it was returning the value “unknown printer (check your Control Panel)”, rather than containing the name of the printer. When I re-installed the default printer, Application.ActivePrinter always returned the proper printer name, whether or not that printer was available for use, and the program stopped crashing.
My problem was a true Heisenbug – it disappeared whenever I re-ran the Excel workbook at random times. That ultimately turned out to help me confirm its diagnosis. Running unattended, sometimes there was no valid printer. When I logged into my account and ran it attended, either it was during the business day or else LogMeIn temporarily assigned my home printer as a valid default printer. This finally made sense of the fact that the program failed only when it wasn’t being closely observed at the time of execution.
In summary, I’d look at inconsistent printer availability and irregular printer installation as possible underlying causes of failure to consistently export .pdf files using Excel VBA.
Frogrammer-Analyst's analysis is great, but the error is not that ambiguous. You will not have this issue if you login to the server using the user that is running the unattended script. But if you sign out and then try rerunning your script unattended you will see that no printers are mapped and {ExportAsFixedFormat} fails for PDF and or XPS formats.
I have found a solution for my case. A true headeache. Maybe it can help others:
Try uncheking the "PDF/A compliant" option under Options dialog when you export as PDF. After that, run the VBA code again.
For my, it was the solution.
PDF Options

Cannot enable folder references in Lotus Notes database

in an external program that accesses various lotus database I get the following error:
Error 4386 occured in line 43: Database does not support folder
references
Usually this program is supposed to enable folder references by itself which doesn't seem to work. So I asked their support and they gave me the following script to enable folder references:
Dim session As New NotesSession
Dim db As NotesDatabase
Set db = session.CurrentDatabase
If db.FolderReferencesEnabled Then
If Messagebox ("Folder References are enabled." & Chr(10) & Chr(10) _
& "Do you want to disable the Folder References?" ,1 + 32,db.title) = 1 Then
db.FolderReferencesEnabled = False
Messagebox "Disabled Folder References now.....", 64, db.title
Else
Exit Sub
End If
Else
If Messagebox ("Folder References are disabled." & Chr(10) & Chr(10) _
& "Do you want to enable the Folder References?" ,1 + 32,db.title) = 1 Then
db.FolderReferencesEnabled = True
Messagebox "Enabeled Folder References now.....", 64, db.title
End If
End If
I get an error in the line db.FolderReferencesEnabled = True saying the same again:
Database does not support folder references
Does anyone have an idea on how I can enable folder references for a database?
EDIT: The database in question is a replication. I was able to enable folder references in the original database and the folder properties are getting copied.
However, the replica still throws this error that it doesn't support folder references if I try to enable them. Is this an expected behaviour?
The database must have the $FolderInfo and $FolderRefInfo hidden views
to support folder references. These views can be copied from the mail
template.
... according to documentation.
Another cause might be an insufficient access level in ACL for NotesID which executes the code.
Sometimes views are broken. Delete views $FolderInfo and $FolderRefInfo and copy these views from mail template back again.
Our Notes admin was finally able to fix this problem by simply running updall, compact, fixup. We can't say which of these utilities actually fixed the problem though.
Administrator Guide for Domino Server maintenance

Resources