Capturing spreadsheet usage throughout a company - vba

We have a lot of customized spreadsheet solutions that are being used and we want some programmatic way of keeping track of them. Obviously since they are spreadsheets, people can save them locally, rename them, etc so we need a solution that can account for that.
Some ideas are:
On spreadsheet open, handle the OnOpen event and write a message to a database for tracking
the issues with this are where do we store database details. If the database is down, we dont want the spreadsheet to crash, etc
has anyone come up with a good spreadsheet inventory management solution that handles all the issues above.

I don't understand the problem you're trying to solve here: you don't need spreadsheet usage logging as an end-result, something is causing pain and this is what you've devised to try to fix it.
If you need seriously reliable logging of all spreadsheet usage, then I don't think this is going to work. If you need mostly reliable logging, then just use a database and don't worry about the (rare) occasions that the database is down. On Error Resume Next should be enough to ensure the spreadsheet continues in that event.
That said, I'd be more inclined to go for a web-based solution: that way you don't have to get involved with ensuring everyone has the necessary database drivers, working connection strings and other horridness.
Some more awkward questions that are making me think that you may need another approach:
How are you going to deploy changes to your logging solution?
Do your users have control over their macro security level? Or the ability to write and edit macros? Could they therefore (innocently or otherwise) disable logging?
Can the users operate offline? What happens then?

Have the excel spreadsheet make a request out to a web server.
Add msinet.ocx to your toolbox and create a form with the Inet control. Add the ocx by right clicking somewhere in the toolbox area.
Then you can set the location of the Inet control somewhere you can handle that the spreadsheet was opened.

Although you may need logging in the short term, the long term solution should be to bring your spreadsheets under control. You should gather the "definitive" copy of the spreadsheets, and move them to a file share, where they will all be protected - users will be able to change the data in them, but will be unable to change the formulas.
If you need a more controlled collaboration solution, then you should look into using SharePoint, possibly the MOSS version which has Excel Services on it.
You might also need to explore how the spreadsheets are being used. Perhaps they are being used instead of someone writing a program, and in some cases, it may be time to do that.
Lastly, you don't want to track spreadsheet usage - you don't care if someone creates a spreadsheet to track their kid's soccer team scores. It's particular spreadsheets you're interested in. The logging may help you track that down to start with, but that's all it can help you with.

I like the suggestions being made so far and what you wrote. I personally like to keep things simple so here's my humble suggestion. It sounds like you have a lot of templates you may be managing and with excel things get messy quick and it's hard to know that formulas are not being tampered with. With that in mind I'd forget any database change management solution, instead:
Create a share drive folder that's set to read only and accessible by everyone in the company
You can create a sub folder structure that makes sense by team, department, location, whatever works
Store the latest copies of the excel templates in the folders
I'd also suggest locking the templates that have critical calculations in them
--> Try to leave it as open as you can so they can be customized where they need be but at your discretion
You may also consider setting up a version control repository that manages the changes to this folder structure. Look into version control with a simple interface like tortoiseSVN so you can track what changes were made and when. The standard share drive back ups are a life saver but I'd still supplement with a version control system (just makes things a little easier). Here's a couple of links to help you get started, you can try subversion locally and see what you think:
Instructions to setup Subversion on Windows
Tortoise Client to interact with Subversion
Also note, IF you chose to implement some kind of database connection for a spreadsheet to perform logging on a database server as has already been noted you can use "on error resume next". Here's what you can do:
After resume next attempt to open the connection to the DB
You can choose to handle the error then with an if statement such as:
if err.number = 3024 then
msgbox "Database file not found, check network connection and retry"
exit
end if
Here's a link to look up additional error codes for trapping in similar fashion:
Error Trapping in VBA

I do something very similar to this to check the current version of the Excel application. You could just as easily use this same code to make a web-request to a server that will log 'hits'. Here's my code:
In ThisWorkbook:
Option Explicit
Private Sub Workbook_Open()
Updater.CheckVersion
End Sub
Elsewhere (in a module called Updater)
Option Explicit
Const VersionURL = "http://yourServer/CurrentVersion.txt"
Const ChangesURL = "http://yourServer/Changelog.txt"
Const LatestVersionURL = "http://yourServer/YourTool.xlsm"
#If VBA7 Then
Private Declare PtrSafe 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
#Else
Private 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
#End If
Public Sub CheckVersion()
On Error GoTo fail
Application.StatusBar = "Checking for newer version..."
Dim ThisVersion As String, LatestVersion As String, VersionChanges As String
ThisVersion = Range("CurrentVersion").Text
If ThisVersion = vbNullString Then GoTo fail
LatestVersion = FetchFile(VersionURL, , True)
VersionChanges = FetchFile(ChangesURL, , True)
If LatestVersion = vbNullString Then
Application.StatusBar = "Version Check Failed!"
Exit Sub
Else
If LatestVersion = ThisVersion Then
Application.StatusBar = "Version Check: You are running the latest version!"
Else
Application.StatusBar = "Version Check: This tool is out of date!"
If (MsgBox("You are not running the latest version of this tool. Your version is " & _
ThisVersion & ", and the latest version is " & LatestVersion & vbNewLine & _
vbNewLine & "Changes: " & VersionChanges & vbNewLine & _
vbNewLine & "Click OK to visit the latest version download link.", vbOKCancel, _
"Tool Out of Date Notification") = vbOK) Then
ShellExecute 0, vbNullString, LatestVersionURL, vbNullString, vbNullString, vbNormalFocus
End If
End If
End If
Exit Sub
fail:
On Error Resume Next
Application.StatusBar = "Version Check Failed (" & Err.Description & ")"
End Sub
As you can see, error handling is in place to make sure that if the URL is unavailable, the app doesn't crash, it just writes a message to the user in the status bar.
Note that if you don't want to set up a web service that does this, you could try to have the spreadsheet write to a database - you could still re-use a lot of this code, but not as much of it.

Your idea is good. Database availability is usually higher than the availability of the users' laptop. And there is a kind of primitive error (exception) handling in VBA, so they won't necessarily see freaking error messages.
Yes, you have a loss. Any uses of the sheet saved offline when the user is not on your network - will be missing from the database. But I don't think that there's a 100% foolproof solution for this.
Try to search for a Financial Times article like "Excel - a tool that is too ad hoc and open for errors". Even the title says it all.

write to the db, if the write fails, catch the error and send an e-mail to someone that can manually increment the count when the database is back up.

You could do a file-based approach with any of several file integrity monitoring solutions. Samhain is one free open source example. That would allow your employees to access their spreadsheets without interference, but would report when new spreadsheets are discovered or when their timestamps or hash values change. It would also detect changes made while the developer was off-line (on their laptops, for example) once they've reconnected to the network.

Related

How to Refresh Excel Smart View Essbase using Macro

I'm using below code to refresh Essbase feeds in my workbook and it is working nicely, however, the only downfall is that I need to enter password every time I refresh the essbase as our Essbase system is highly secured.
My question is, is it possible to incorporate the Password in the macro so that I don't have to enter the password every time I refresh the feeds.?
Solving this problem would also enable me to automate this whole process through Python and schedule a job.
Private Declare PtrSafe Function HypMenuVRefreshAll Lib "HsAddin" () As Long
Sub RefreshHFM()
Call HypMenuVRefreshAll
End Sub
Any help.?
Thanks.
The HypMenuVRefreshAll command is basically the equivalent of clicking on the refresh button, and of course it is going to prompt you for a password because that's exactly what would happen if you clicked on the menu yourself. There are other commands, however, for the other menu items as well as the actual API that can be used to connect. You can connect with the following code:
Private Sub cmdConnect_Click()
Dim lReturn As Long
Dim sMessage As String
''' try to connect
lReturn = EssVConnect("sheet name", "admin", "password", "epmvirt11124", "sample", "basic")
''' show a message if necessary
If lReturn <> 0 Then
sMessage = EssVGetLastErrorMessage()
MsgBox "EssVConnect status = " & lReturn & ". Error Message = " & sMessage
End If
End Sub
I have borrowed this code from a button that connects to a specific cube. Be sure to update the username, password, server name, application, and cube to match your environment.
Please also note that this is part of the "old" Essbase VB API that works with the "classic" Excel add-in. The code is different for Smart View, which came with a completely different VB API.

How to run a Classic ASP file (located on a server) from VBA code?

Last few days I was working on a Outlook 2013 function which reads an email and saves all data of the email. This is being done in the VBA code of Outlook and all works fine. The stored VBA data is then transferred to a XML file on the server which also works.
What I want to do next is read the transferred XML Data in the ASP file (which is also located on the server) and INSERT the data into an MS SQL server and then removing the XML file.
This all works fine as well since I tested it by manually calling the asp file on the web.
Though the thing I cant seem to find out is how to activate/launch the ASP file from within the VBA code automatically instead of calling it myself manually.
So when the Macro is being clicked in Outlook it gets the data, puts it in an XML file and then it should launch the ASP file.
There is an other way to do it, namely by using a Task Scheduler on my server which launches the ASP file every X minutes (and looks for the XML file). This possibility is something I rather avoid though because if a outlook user presses the Outlook macro multiple times in a short time the XML files will overwrite each otter (and thus having the change of not getting ALL the right data).
I didn't add my code since I think it is not really needed here (since the code I have is working), though if code is needed just ask;)
UPDATE
I found a piece of code which opens the asp file on the web (and thus launching it). The problem how ever is that it opens the webpage, while it only should run it. So I should add something that the page is also closed right away (so the user doesn't see it getting opened), now clue if this can be achieved though..
The code for opening it is as follows:
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Public Sub OpenUrl()
Dim lSuccess As Long
lSuccess = ShellExecute(0, "Open", "http://mywebsite.nl/MyCode.asp")
End Sub
which is also located on the server
Do you automate Outlook on the server?
It looks like you need to develop a web service for submitting your data (extracted from Outlook) to the server and run the server sider infrastructure.

How can Excel VBA open file using default application

I want an Excel spreadsheet that has a file path and name in column A. When a macro is run, let's say the file specified in A1 should be opened on the user's machine. The file could be .doc, .xls, .txt, etc.... rather than my vba needing to know the full path the to application, how could I have the vba tell the machine "please open this file and use your application associated with the extension" ?
I have already found this to work with the full path:
dblShellReturned = Shell("C:\Windows\System32\notepad.exe myfile.txt, vbNormalFocus)
how could I get it to work with something like:
dblShellReturned = Shell("myfile.txt", vbNormalFocus) ' how do I get this to work
Thank you in advance!
This works for me in Excel & Word
Sub runit()
Dim Shex As Object
Set Shex = CreateObject("Shell.Application")
tgtfile = "C:\Nax\dud.txt"
Shex.Open (tgtfile)
End Sub
or ... as per Expenzor's comment below
CreateObject("Shell.Application").Open("C:\Nax\dud.txt")
VBA's Shell command wants an exe, so I've been launching the explorer.exe and passing in my file path as an argument. It also seems to work with *.lnk shortcuts and web urls.
Shell "explorer.exe C:\myfile.txt"
The code below is a template. However you might want to update the default (working) directory to the location of the file.
Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpszOp As String, _
ByVal lpszFile As String, ByVal lpszParams As String, _
ByVal LpszDir As String, ByVal FsShowCmd As Long) _
Function StartDoc(DocName As String) As Long
Dim Scr_hDC As Long
Scr_hDC = GetDesktopWindow()
StartDoc = ShellExecute(Scr_hDC, "Open", DocName, _
"", "C:\", SW_SHOWNORMAL)
End Function
I can't comment on existing answers (not enough points), so I'm answering to add information.
Working from Access 2010, I ran into silent failures with the following syntax:
Dim URL As String
URL = "http://foo.com/"
CreateObject("Shell.Application").Open URL
I could get it to work if I wrapped URL in parentheses, but that just seems wrong for subroutine (instead of function) call syntax. I tried swallowing the return value, but that failed with function call syntax, unless I doubled up the parentheses. I realized that the parentheses weren't just syntactic sugar - they had to be doing something, which lead me to believe they might be facilitating implicit casting.
I noticed that Open expects a Variant, not a String. So I tried CVar, which did work. With that in mind, the follwing is my preferred approach since it minimizes the "why are there extraneous parentheses here?" questions.
Dim URL As String
URL = "http://foo.com/"
CreateObject("Shell.Application").Open CVar(URL)
The lesson is that when making OLE Automation calls, be explicit about having Access VBA cast things appropriately!
Shell32.Shell COM object aka Shell.Application can be used that wraps the ShellExecute Win32 API function:
Add a reference to Microsoft Shell Controls And Automation type library to VBA project via Tools->References..., then
Dim a As New Shell32.Shell
Call a.ShellExecute("desktop.ini")
Alternatively, without any references:
Call CreateObject("Shell.Application").ShellExecute("desktop.ini")
Interestingly, here (WinXP), when using a typed variable (that provides autocomplete), ShellExecute is missing from the members list (but works nonetheless).

protecting software to run only on one computer in vb.net

I have developed a small application and now i want to protect it.
I want to run it only on my own computer and i have developed it for myself.
How can i do that?
A. Don't publish it.
B. Hard-code your computer name in the code, and make the first thing the program does to be verifying that System.Environment.MachineName matches it.
You could always check the processor ID or motherboard serial number.
Private Function SystemSerialNumber() As String
' Get the Windows Management Instrumentation object.
Dim wmi As Object = GetObject("WinMgmts:")
' Get the "base boards" (mother boards).
Dim serial_numbers As String = ""
Dim mother_boards As Object = _
wmi.InstancesOf("Win32_BaseBoard")
For Each board As Object In mother_boards
serial_numbers &= ", " & board.SerialNumber
Next board
If serial_numbers.Length > 0 Then serial_numbers = _
serial_numbers.Substring(2)
Return serial_numbers
End Function
Private Function CpuId() As String
Dim computer As String = "."
Dim wmi As Object = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
computer & "\root\cimv2")
Dim processors As Object = wmi.ExecQuery("Select * from " & _
"Win32_Processor")
Dim cpu_ids As String = ""
For Each cpu As Object In processors
cpu_ids = cpu_ids & ", " & cpu.ProcessorId
Next cpu
If cpu_ids.Length > 0 Then cpu_ids = _
cpu_ids.Substring(2)
Return cpu_ids
End Function
Was taken from where: http://www.vb-helper.com/howto_net_get_cpu_serial_number_id.html
Here's a question by Jim to convert this for Option Strict.
It really depends on who is the "enemy".
If you wish to protect it from your greedy, non-cracker, friends, then you can simply have the application run only if a certain password is found in the registry (using a cryptographically secure hash function), or use the MachineName as Jay suggested.
But if you're thinking of protecting it from serious "enemies", do notice: It has been mathematically proven that as long as the hardware is insecure, any software running on it is inherently insecure. That means that every piece of software is crackable, any protection mechanism is bypassable (even secured-hardware devices such as Alladin's Finjan USB product key, since the rest of the hardware is insecure).
Since most (if not all) of today's hardware is insecure, you simply cannot get 100% security in a software.
In between, there are lots of security solutions for licensing and copy-protection. It all comes down to who is the enemy and what is the threat.
No matter how hard you try, if someone really want to run it on another computer, they will.
All need to do is reverse engineer your protection to
remove it
play with it
Another option might be to have your program ask the USER a question that has a derived answer. Here's a brain dead example....
Your Program: "What time is it now?"
You Enter: (TheYear + 10 - theDay + 11) Mod 13
In this way its actually ONLY YOU that can run the program instead of it being MACHINE dependent.
I have made things like this in VB DOS.
I either made a non-deletable file that is key to a specific machine with a code inside, and/or read the .pwl files and have several checks, that are only on your machine. The non-editable file is made with extended character sets like char 233 so when a person tries to look at it, it will open a blank copy (edit) (write.ex), so data cannot be read and it cannot be edited moved or deleted.
It needs to be certain characters; I am not sure if every charter between 128 and 255 will work it, some extended characters work to do this some will not, also it can be defeated, but it will keep some people out,
But it can be read or checked in a program environment. Nothing is totally secure, this is some of the things I mess with.
Note: the file will be very hard to delete, maybe make a test directory to test this.
I hope this is OK I am not very good at conveying info to people; I have programmed since 1982.
Another idea ... I wrote a program that cannot be run directly, it is only ran by an external file, so you could add in a password entry section to it and encrypt password so it cannot be read very easily ,I made an executable version of a vb program to test. it writes in to slack space a character so if the program sees that value it will not run, BUT the runner program has a different character, and it changes it to that character ,and the program is designed to only let in if the character is the proper one ,made only by the runner , then when it enters it changes it back so it is not left open , I have made this sorta thing, and it does work, there is always a way to defeat any protection , the goal is to slow them down or discourage them from running or using your program if you do not want them to.I may include examples at a later date.

Use VBA to call a cellphone

About a year ago, a manager in another department brainstormed that I could code up some VBA to auto call me in the event one of my automated reports crashes. I laughed at the time, but my skills have improved considerably and I wonder if it's technically possible
(not that I'd actually do it, mind you. I like my early Saturday mornings workplace-free).
This would need:
1. Access to the internet (not a problem)
2. A means of connecting to some service to place the call, preferably free, lest I cost the company $10 a month (Skype?)
3. An automated voice (already exists on the standard Access install package)
What do you think?
Edited 08/24/2009 - Spacing added. No text was changed.
Do the simplest thing that could possibly work. In this case, making phonecalls is hard, but sending emails is easy.
Most cellphone providers expose a phone's mailbox (something like 555-867-5309#cellphoneprovider.com) to the internet, allowing you to send an email to that address and have it show up on your phone as a text message.
You can use Skype in combination with VBA. It's actually not that complicated and you will find a couple of samples written in VBScript on the Skype website. I don't know whether it is possible to actually play an audio file, but you can send SMS easily:
'// Create a Skype4COM object:
Set oSkype = WScript.CreateObject("Skype4COM.Skype", "Skype_")
'// Start the Skype client:
If Not oSkype.Client.IsRunning Then oSkype.Client.Start() End If
'// Send SMS:
Set oSMS = oSkype.SendSms("+1234567890", "Hello!")
WScript.Sleep(60000)
'// Message event handler:
Public Sub Skype_SmsMessageStatusChanged(ByRef aSms, ByVal aStatus)
WScript.Echo ">Sms " & aSms.Id & " status " & aStatus & " " & oSkype.Convert.SmsMessageStatusToText(aStatus)
End Sub
'// Target event handler:
Public Sub Skype_SmsTargetStatusChanged(ByRef aTarget, ByVal aStatus)
WScript.Echo ">Sms " & aTarget.Message.Id & " target " & aTarget.Number & " status " & aStatus & " " & oSkype.Convert.SmsTargetStatusToText(aStatus)
End Sub
If you have a old dial up modem, then you could (in 'old VB6 days) dial via the modem programmatically, however I'm not sure if its possible in VBA. The next challange would be to get the audio down the line.
I would suggest that you butcher a headless earphone & microphone that connects to phones, you could then take a 3.5mm audio jack from your PC speaker output and connect this to the headless earphone/microphone set, unless there are cables that already do that (possibly).
Then it would be a simple matter of coding up Microsofts 'text to speech' engine.
Darknight
http://chandoo.org/wp/2009/02/05/twitter-from-excel/. Set up a twitter account that pings your phone and create twitters with this.
It's not as easy as the email idea, but you could be the first person to tweet from Excel for a reason other than novelty.
Another quite simple option is to send yourself a text message which is almost but not quite as easy to do as sending an email, but much easier to recieve. Companies such as clickatell.com provide cheap web based text services with good api's where once you are signed up all you need do is call a URL and you can send a text message.
Well worth a try.