views:

88

answers:

3

Hey all, have been working on designing a new database for work. They have been using Excel for their daily reports and all the data is stored in there, so I decided to have the back-end of the database in Access and the front-end in Excel, so any analytical work can be easily performed once all the data has been imported into Excel.

Now I'm fairly new to VBA, slowly getting used to using it, have written some code to transfer one of the calculated tables from Access to Excel:

Option Explicit

Public Const DataLocation As String = "C:\Documents and Settings\Alice\Desktop\Database\TestDatabase21.accdb"

Sub Market_Update()
    Call ImportFromAccessTable(DataLocation, "Final_Table", Worksheets(2).Range("A5"))
End Sub

Sub ImportFromAccessTable(DBFullName As String, TableName As String, TargetRange As Range)

    Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer

    Set TargetRange = TargetRange.Cells(1, 1)
    ' open the database
    Set cn = New ADODB.Connection
    cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";"
    Set rs = New ADODB.Recordset
    With rs
        ' open the recordset
        ' .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable

        ' all records
        .Open "SELECT * FROM Final_Table", cn, , , adCmdText
        ' filter records

        For intColIndex = 0 To rs.Fields.count - 1 ' the field names
            TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
        Next
        TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data

    End With
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

Sub Company_Information()

   Dim companyName As String

On Error GoTo gotoError

   companyName = Application.InputBox(Prompt:="Enter Company Name", _
                           Title:="Company Name", Type:=2)                  

    Exit Sub 'Don't execute errorhandler at end of routine

gotoError:
    MsgBox "An error has occurred"

End Sub

The above code works fine and pulls up the desired calculated table and places it in the right cells in Excel.

I've got two problems that I'm having trouble with; firstly I have some cell-formatting already done for the cells where the data is going to be pasted into in Excel; I want it to apply the formatting to the values as soon as they are pasted in Excel.

Secondly; I have an add-on for Excel which updates some daily Stock Market values; these values need to be transferred into Access at the end of each working day, to keep the database maintained, I tried some code but have been having some problems with it running.

The code for this part can be seen following:

Sub UPDATE()

   Dim cnt As ADODB.Connection
   Dim stSQL As String, stCon As String, DataLocation As String
   Dim stSQL2 As String

   'database path - currently same as this workbook
   DataLocation = ThisWorkbook.Path & DataLocation
   stCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
   "Data Source=" & DataLocation & ";"
   'SQL code for GL Insert to Access
   stSQL = "INSERT INTO Historical_Stock_Data SELECT * FROM [Portfolio] IN '" _
   & ThisWorkbook.FullName & "' 'Excel 8.0;'"

   'set connection variable
   Set cnt = New ADODB.Connection
   'open connection to Access db and run the SQL
   With cnt
        .Open stCon
        .CursorLocation = adUseServer
        .Execute (stSQL)
   End With
   'close connection
   cnt.Close

   'release object from memory
   Set cnt = Nothing

End Sub

I get the following error with this.

Run-time Error '-2147467259 (80004005)'

The Microsoft Jet database engine cannot open the file 'Cocuments and Settings\Alice\Desktop\Database'. It is already opened exclusively by another user or you need permission to view its data.

I'm fairly new to databases, VBA and Access so any help would be greatly appreciated.

Also I have been told that the above method of having an Excel front-end and Access back-end is not recommended but alot of the analysis they conduct is done through Excel, and the charts feature in Excel is much better than Access in my experience atleast; and that is also one of the requirements for this project.

Thank you advance!

+2  A: 

Do the data entry/updating/reviewing in Access. One of Access' strengths is using forms that allow you to update the tables without any code. Then allow the users to easily export the data to Excel such as by clicking on some command buttons.

Modules: Sample Excel Automation - cell by cell which is slow

Modules: Transferring Records to Excel with Automation

Tony Toews
Thing is Tony, I was trying to make a sort of Dashboard in Excel so the user could do everything from there, without even worrying about what's happening in the back in Access. Another thing is, the updating needs to take place from values in Excel, because of the Add-on that I have which gets the latest StockPrice values straight into a spreadsheet, I'm not to familiar with how Linked tables work, but would it be possible to do that on the Access side, by linking a particular spreadsheet? Problem is, the values in Excel need to be refreshed before they goto Access.
Muffi D
Ah, well, you enver said that in your initial posting. <smile> Is this Bloomberg data? If so I've worked with the API directly to pull in data into a table.
Tony Toews
Actually it isn't bloomberg data, the bosses wanted a cheap solution so I found this add-on for Excel, which gets its values from yahoo finance and msn, the values get pulled into Excel at the end of each working day, since the database only needs to store the end of the day share price and volume, I thought it was a reasonable option to do it that way. The second piece of code is supposed to pull that data into the specific Access table, now again my VBA isn't that strong but I'm learning as I go, so in this regards any help would be appreciated.
Muffi D
A: 

nothing wrong in principle with the excel/access pairing. I'm not familiar with ADO (I use DAO), but your error message seems to be indicating that the path to the datasource is not fully formed; or you already have it opened and hence are locking it.

alastair harris
A: 

Solution to your first problem:
Sorry to be the bearer of bad news, but your entire first module is unnecessary. Instead, try:

  1. Go to Data->Import External Data->Import Data, select your Access file, select your table, and presto! done!
  2. Right-click on your new "External Data Range" to see a number of options, some related to formatting. You can even keep the original cell formatting and just update the values. I do this all the time.
  3. To update the Excel data table later, there is a "External Data Range" toolbar that allows you to refresh it as well as a "refresh all" option to refresh every table in the Excel file. (You can also automate this thru code. It'll take some trial and error, but you're definitely up to the task)

Regarding your second problem
I've never used it, but there is also a "New Web Query" option in there as well. I assume it can be manipulated and updated the same way.

And lastly
Your choice of the Excel front-end and the Access back-end sounds good for your needs. It gets the data to your analysts in a medium they are familiar with (Excel) while keeping the calculations out of the way in Access. Technically, you could try putting all your calculations in Excel, but that might the Excel file much bigger and slower to open.

alt text

PowerUser
Hey, that is very helpful, but the only thing is, if you check, I need to be able to output single company related data easily as well, so for example if someone enters a company name in the form, only that particular companies Stock market data, financial data and a number of different graphs showing performance come up. Again I'm fairly new to Access and VBA, so maybe the solution will take some time to come with regards to this, either way, it would have to be done in some sort of code, especially if I want to automate the graph/charts generation as well.
Muffi D
If you do the above method then choose **Data->Filter->AutoFilter**, you can get drop-down menus for some or all of your column headers (You'll see a down-facing arrow at the top of each column). This way, they get a familiar interface for picking companies (It is a little problematic if you have alot of companies, like 100+)
PowerUser
As for using code, it does allow you to do pretty much anything. So go for it.
PowerUser
Ok, thanks for that, I could whip up a sort of Dashboard on Excel to be able to do this, this does eliminate the use of code on the Excel side for a number of things. The only other problem that I'm having now is with regards to updating the Access database from values that have been refreshed from Excel; best way to manipulate that without actually entering Access? Because I don't want them to even touch the Access parts of the database, I want them to be able to do everything from Excel.
Muffi D
Well, after Excel imports a "master" table, the user can select only the items they need using the autofilter. (Of course, the catch is that they can look at anything else in the table too, but if security isn't an issue, then this isn't a problem). Using your example, what parameters do you need to pass to Access that can't be filtered out on the Excel side?
PowerUser
Well basically, the access database needs to be maintained on a daily basis. This is with the Daily stock market prices plus various currency prices, now the bosses wanted the cheapest solution, so I found this add-on for Excel which can download the latest Stock and currency prices for whatever company or currency. So I made a little sheet which has all this information on it, my idea was to update all these values into the right Access table at the end of each day, once that update is performed, a Market update report is generated and it is to be mailed to everyone in the company.
Muffi D
Also, the way the add-on works is, you press Refresh anytime, its got a little formula which gets the latest Stock Market prices for whatever companies you have listed there
Muffi D
Sounds like a good plan. Not the fanciest, to be sure, but it gets the job done. Well, as I said earlier in my post, once you import the data, you can use Excel's Refresh button (probably the same one you mentioned) to refresh it from Access. And everything we've talked about so far can be automated with VBA that's stored in a separate "controller" file and kicked off via command line.
PowerUser
Actually the refresh button in this case is slightly different then the one that you mentioned, its from this add-on http://www.jabsoft.com/stock_quotes_for_excel/stock_quotes_for_excel.htm I think it's quite handy actually, solved a few problems for me when it comes to coding and getting data from online, since I'm not that great at coding! They have a 15 day trial if anyone wants to check it out.
Muffi D