Excel 2007 Macro ,VBAProject can put a configuration file? - excel

Firstly, I'm a newer to Excel Macro.
I have read some articles and done some work these days.
But now I'm so hesitant.Can .txt or .xml file be placed into VBAProject?If yes,how place and how to get the path of file or just read the file? If no, is there a transit way to do this work? Just think Macro,not AddIn project.
Thanks very much!

You can save a txt with ini extension and save your settings in it as key value pairs. With below code you can retrieve those settings providing the key and getting the value.
Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Public Function GetINIString(ByVal sApp As String, ByVal sKey As String, ByVal filepath As String) As String
Dim sBuf As String * 256
Dim lBuf As Long
lBuf = GetPrivateProfileString(sApp, sKey, "", sBuf, Len(sBuf), filepath)
GetINIString = Left$(sBuf, lBuf)
End Function
Sub sample()
Dim Path As String
Path = ThisWorkbook.Path & "\" & "Path.ini"
Link = GetINIString("Path", "Link", Path)
End Sub
Please save the .ini file in the same folder where the workbook resides or you may change the Path variable accordingly.
You may also refer this link for more details.

Related

Download Excel file from Sharepoint, Save to Desktop

I am trying to download an excel file stored in sharepoint (no unc path available) to my desktop.
This code below seems to work and create "CST.xlsx" but I get an error msg:
Notes:
Url for excel file is taken directly from the web address bar and everthing after ".xlsx" is removed.
Code:
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Function DownloadFileFromWeb(strURL As String, strSavePath As String) As Long
' strSavePath includes filename
DownloadFileFromWeb = URLDownloadToFile(0, strURL, strSavePath, 0, 0)
End Function
Sub download()
Call DownloadFileFromWeb("url.xlsx", "Desktop\download\CST.xlsx")
End Sub
See my answer in this thread about the same problem for a workaround.

printing specific pages form pdf file using print scope string

I need to print selected pages of *.pdf file using excel VBA.
I need to do this not by providing scope "from - to" but giving scoope of pages like "1-3,4,8, 17-25"
I can only print whole file using below code:
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Public Function PrintThisDoc(formname As Long, FileName As String)
On Error Resume Next
Dim X As Long
X = ShellExecute(formname, "Print", FileName, 0&, 0&, 3)
End Function
Sub testPrint()
Dim printThis
Dim strDir As String
Dim strFile As String
strDir = "C:\Users\any\Desktop"
strFile = "somefile.pdf"
printThis = PrintThisDoc(0, strDir & "\" & strFile)
End Sub ```
Judging from this post, it is not possible using ShellExecute alone. What you would need is to write a script which will open the file in whatever PDF reader you have installed, find a "Print" button there and provide all the options. This will take a huge amount of work and will depend on the version of Windows and the PDF reader, so basically it will work only for you, and not for other users.
If you want to go this path though, take a look at FindWindow and SendMessage WinAPI functions.

How to download the canonical revision?

In my Excel workbook I use VBA code that calls URLDownloadToFile to download a different Excel file stored in SharePoint to the current folder of the workbook.
The downloaded workbook is not the latest / canonical revision. The link used as a parameter for URLDownloadToFile is the one that links directly to the file, NOT to a specific revision with "_vti_history".
I tried updating the file on SharePoint multiple times to test this but the same old revision was downloaded every time.
Edit: To clarify, the issue.
I call the function as
URLDownloadToFile(0, "http://blahblah/file.ext", "C:\blah\file.ext", 0, 0)
The local copy saved is not the latest revision of "file.ext" but an older one.
If the URL used is the same to download the newest version, it may be that a cached version is being downloaded by URLDownloadToFile.
Try to clear the cache for the link before downloading by using DeleteUrlCacheEntry:
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" Alias "DeleteUrlCacheEntryA" (ByVal lpszUrlName As String) As Long
Sub downloadFile()
Call DeleteUrlCacheEntry("http://blahblah/file.ext")
Call URLDownloadToFile(0, "http://blahblah/file.ext", "C:\blah\file.ext", 0, 0)
End Sub
I have been trying to figure this out. The function URLDownloadToFile was not working for Sharepoint Online as it couldn't navigate the authentication part. Finally, I found this link which saved my day. The solution that worked for me Version 1 as I didn't have access to the folder view of the file, I only had direct access to the file alone. I created the following function and added the reference to Windows Script Host Object Model library in VBA.
Public Sub VBA_FileCopy(ByVal sSourceFile As String, ByVal sDestinationFile As String)
Dim fs As FileSystemObject
Set fs = New FileSystemObject 'CreateObject("Scripting.FileSystemObject")
sSourceFile = Replace(sSourceFile, "/", "\")
sSourceFile = Replace(sSourceFile, "http:", "")
sSourceFile = Replace(sSourceFile, "https:", "")
sSourceFile = Replace(sSourceFile, Split(sSourceFile, "\")(2), Split(sSourceFile, "\")(2) & "#SSL\DavWWWRoot")
sSourceFile = Replace(sSourceFile, " ", "%20")
fs.CopyFile sSourceFile, sDestinationFile, True
End Sub

Automated download of excel file in vba

I've had a look around and I think I need some very specific help. I need to write a macro to download excel files online. Until now I have been able to use the URLdownloadtofile function by adding the get request parameters to the URL. The website I need to download from this time however doesn't seem to work that way. (It ends in aspx, if that makes a difference). I use http fox addin on Firefox to see the request line and all it gives is the website and no parameters after it. How can I use xmlhttp to download this file if I can't use URLdownloadtofile? Also one of the dropdown menus only becomes active when the previous menu value is selected.
The URL of the file is: http://cmg.cdec-sic.cl/Modulos/CMg/CDEC_CMgBarras.aspx
If I want the excel file for January 2014, tension 220 and barra alto jahuel_220 for instance, what would I need to place after the send function of the xmlhttp function? As in what parameters? I tried using the names of each parameter = to the value I want. And I changed all the $ to the hex value. But it just seemed to return the same page.
And once that works, how do I get the returned excel file to download to a specific directory?
Any help would be greatly appreciated.
Option Explicit
Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Dim Ret As Long
Sub Download_Files_from_web_and_save_to_file()
Dim strURL As String
Dim strPath As String
Ret = URLDownloadToFile(0, " http://cmg.cdec-sic.cl/Modulos/CMg/CDEC_CMgBarras.aspx", "d:\my_file.xls", 0, 0)
If Ret = 0 Then
' MsgBox "File successfully downloaded"
Else
MsgBox "Unable to download the file"
End If
End Sub

How do I issue an HTTP GET from Excel VBA for Mac

I need to issue an HTTP Get with a query string to a web service from Excel for Mac 2011. I've seen the answers for using QueryTables (How can I send an HTTP POST request to a server from Excel using VBA?) but they use the POST method, not a GET method. I also see that it's easy from a Windows machine, but I'm stuck on a Mac.
Any suggestions, or is it hopeless?
Doing further research, I came across Robert Knight's comment on this question VBA Shell function in Office 2011 for Mac and built an HTTPGet function using his execShell function to call curl. I've tested this on a Mac running Mac OS X 10.8.3 (Mountain Lion) with Excel for Mac 2011. Here is the VBA code:
Option Explicit
' execShell() function courtesy of Robert Knight via StackOverflow
' https://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac
Private Declare Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As Long
Private Declare Function pclose Lib "libc.dylib" (ByVal file As Long) As Long
Private Declare Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As Long, ByVal items As Long, ByVal stream As Long) As Long
Private Declare Function feof Lib "libc.dylib" (ByVal file As Long) As Long
Function execShell(command As String, Optional ByRef exitCode As Long) As String
Dim file As Long
file = popen(command, "r")
If file = 0 Then
Exit Function
End If
While feof(file) = 0
Dim chunk As String
Dim read As Long
chunk = Space(50)
read = fread(chunk, 1, Len(chunk) - 1, file)
If read > 0 Then
chunk = Left$(chunk, read)
execShell = execShell & chunk
End If
Wend
exitCode = pclose(file)
End Function
Function HTTPGet(sUrl As String, sQuery As String) As String
Dim sCmd As String
Dim sResult As String
Dim lExitCode As Long
sCmd = "curl --get -d """ & sQuery & """" & " " & sUrl
sResult = execShell(sCmd, lExitCode)
' ToDo check lExitCode
HTTPGet = sResult
End Function
To use this, copy the code above, open the VBA editor in Excel for Mac 2011. If you don't have a module, click Insert->Module. Paste the code into the module file. Leave the VBA editor (clover-Q).
Here's a specific example using a weather forecast web service (http://openweathermap.org/wiki/API/JSON_API)
Cell A1 will be reserved for the name of the city.
In cell A2, enter the URL string: http://api.openweathermap.org/data/2.1/forecast/city
In cell A3 which will build the query string, enter: ="q=" & A1
In cell A4, enter: =HTTPGet(A2, A3)
Now, type a city name in cell A1, for example London, cell A4 will show you the JSON response containing the weather forecast for London. Change the value in A1 from London to Moscow -- A4 will change to the JSON-formatted forecast for Moscow.
Obviously, using VBA, you could parse and reformat the JSON data and place it where needed in your worksheet.
No claims for performance or scalability, but for a simple one-shot access to a web service from Excel for Mac 2011, this seems to do the trick and met the need for which I posted my original question. YMMV!
The answer above from John Stephens is fantastic (please upvote it!), but it no longer worked for me in the more recent Excel:mac 2016, with an error that the code needs to be updated for use on 64-bit systems.
Taking some tips from an issue I found in a related repository, I was able to adjust the data types in John's script to work correctly in Excel:mac 2016:
Option Explicit
' execShell() function courtesy of Robert Knight via StackOverflow
' http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac
Private Declare PtrSafe Function popen Lib "libc.dylib" (ByVal command As String, ByVal mode As String) As LongPtr
Private Declare PtrSafe Function pclose Lib "libc.dylib" (ByVal file As LongPtr) As Long
Private Declare PtrSafe Function fread Lib "libc.dylib" (ByVal outStr As String, ByVal size As LongPtr, ByVal items As LongPtr, ByVal stream As LongPtr) As Long
Private Declare PtrSafe Function feof Lib "libc.dylib" (ByVal file As LongPtr) As LongPtr
Function execShell(command As String, Optional ByRef exitCode As Long) As String
Dim file As LongPtr
file = popen(command, "r")
If file = 0 Then
Exit Function
End If
While feof(file) = 0
Dim chunk As String
Dim read As Long
chunk = Space(50)
read = fread(chunk, 1, Len(chunk) - 1, file)
If read > 0 Then
chunk = Left$(chunk, read)
execShell = execShell & chunk
End If
Wend
exitCode = pclose(file)
End Function
Function HTTPGet(sUrl As String, sQuery As String) As String
Dim sCmd As String
Dim sResult As String
Dim lExitCode As Long
sCmd = "curl --get -d """ & sQuery & """" & " " & sUrl
sResult = execShell(sCmd, lExitCode)
' ToDo check lExitCode
HTTPGet = sResult
End Function
Another option (update accordingly if your curl is not located in /opt/local/bin/curl):
VBA:
Public Function getUrlContents(url) As String
Dim command As String
command = "do shell script ""/path_to/getUrl.sh " + url + """"
getUrlContents = VBA.MacScript(command)
End Function
/path_to/getUrl.sh:
#!/bin/sh
if [ -z "$1" ]
then
echo "missing url argument"
else
/opt/local/bin/curl "$1"
fi
Note that you will have to ensure that getUrl.sh is executable:
chmod u+x getUrl.sh

Resources