I am trying to use the Windows 8 Location API in order to get GPS coordinates from a built-in sensor, and return these coordinates to MS Access. However, due to the unsupported variant types used in the API, Access is unable to reliably use its objects. I am trying to come up with a workaround using a VBScript file, and somehow returning the values to MS Access (using 2010 and 2013). The easiest way I could think of was to spit out a txt file to be read by Access and then deleted.
My VBS File works perfectly when I run it from Windows Explorer (double-clicking the file) but I can't find a way to make it work properly when running it from VBA code. Here is the VBS File:
Dim latlongfactory
Dim rptLong, rptLat
Dim report
Dim keepSleeping
Dim fs, f
Dim ts
Set latlongfactory = Wscript.CreateObject("LocationDisp.LatLongReportFactory", "llf_")
Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
f = fs.BuildPath(CurrentDirectory, "gpsTempFile.txt")
keepSleeping = True
latlongfactory.ListenForReports(1000)
Sub llf_NewLatLongReport(report)
rptLong = report.Longitude
rptLat = report.Latitude
keepSleeping = False
End Sub
Do While keepSleeping
Wscript.Sleep(20)
Loop
Set ts = fs.CreateTextFile(f, True)
ts.WriteLine rptLat & "," & rptLong
ts.Close
Set fs = Nothing
Set latlongfactory = Nothing
set report = Nothing
When run through VBA, it doesn't create the text file anymore, and I'm not entirely sure why. I tried adding a Msgbox at the end of the script just to see if the code was running. The Msgbox does come up.
The line I use to execute in Access VBA is:
Shell "Wscript """ & CurrentProject.Path & "\gpscoordinates.vbs""", 1
It runs the VBS file, but the text file isn't getting created and I cannot figure out why. Any help would be much appreciated!
If you want the output file to be created in the same folder in which the script resides, you can use the ScriptFullName property of the WScript object:
outputFolder = fs.GetParentFolderName(WScript.ScriptFullName)
f = fs.BuildPath(outputFolder, "gpsTempFile.txt")
Related
One of my datasources comes as Excel "xls" files. I put that in quotes because, under the hood, the authoring system has generated an html file and named it myFile.xls.
When manually opening this, Windows gives me a warning, but Excel will open it. From Excel VBA, I can inhibit-warning, and it opens silently and correctly. But trying to open a folder full of such files, PowerQuery just hangs. I've been manually opening each "xls" file and saving as .xlsx. Any suggestions for getting rid of this manual step?
[Running Excel 2013 under Windows 7.]
Add a reference to Microsoft Scripting Runtime in order to use the Scripting.FileSystemObject object.
Dim app As Excel.Application
'If macro is running within an Excel instance, and you want to use that instance uncomment the next line
'Alternatively, use Application directly
'Set app = Application
'If you want to create a new instance, uncomment the next line
'Set app = New Excel.Application
Dim fso As New Scripting.FileSystemObject
Dim sourceFolder As String
sourceFolder = "C:\path\to\folder\of\pseudo-excel-files"
Dim destFolder As String
destFolder = fso.BuildPath(sourceFolder, "_converted")
If Not fso.FolderExists(destFolder) Then fso.CreateFolder(destFolder)
Dim fle As Scripting.File
For Each fle In fso.GetFolder(sourceFolder).Files
Dim destPath As String
destPath = fso.BuildPath(destFolder, fle.Name & ".xlsx")
Dim book As Workbook
Set book = app.Workbooks.Open fle.Path
book.SaveAs destPath, xlWorkbookDefault
book.Close
Next
I am attempting the following in an AccessDb via VBA:
Export a single table from current DB into a new DB in the same directory, via a Query/TransferDatabase. This seems to work as expected.
Dim ws As Workspace
Dim db_new as Database
strPath = CurrentProject.Path & "\Backend_Database\"
strDBFilename = strPath & Raw_Count_File.accdb"
Set ws = DBEngine.Workspaces(0)
Set db_new = ws.CreateDatabase(strDBFilename, dbLangGeneral)
DoCmd.TransferDatabase acExport, "Microsoft Access", _
strDBFilename, acTable, "tmp_RawCountFile", "Raw_TblMatchedTB"
Within the same function used above (to create the new file), I am attempting next to ZIP the new file into the same directory. The result is 1K Byte ZIP file (it's an empty ZIP ).
If I breakout the code segment that creates the ZIP file into separate function (i.e., under another button), the function works as expected and the proper ZIP file is created.
My Question:
I am guessing the new DB file and subsequent TransferDatabase is leaving the new_db file hanging open and inaccessible to the ZIP function. I attempted to set the various objects = nothing prior to the ZIP function, but same result. Only if I exit the first function and call a second function will it work as desired.
Can I add something to the end of the TransferDatabase function to ensure the resulting file will be available for the ZIP task?
My preference is not to add a secondary button press to this task...
Any suggestions to get me going?
Thanks!
Try to Set db_new = Nothing before zipping, in order to close the newly created db.
I'm writing contents of tables from access to excel(Opening the excel file from access) After writing it i'm trying to save all workbooks in the appXL application. For that i'm making DispalyAlerts false before saving and trun on back after saving. After writing contents to excel i'm closing the access. After writing ,when i'm trying to close the excel, it is not giving any alerts like Do you want to save the contents?
My vba code
Sub Writexl()
Dim appXL As Excel.Application
Dim wb As Excel.Workbook
StrwbPath="C:\temp\sample.xls"
Set appXL = CreateObject("Excel.Application")
With appXL
Set wb = .Workbooks.Open(StrwbPath)
.Visible = True
End With
'here code for writing contents
'save workbook after writing
appXL.Application.DisplayAlerts = False
For Each w In appXL.Application.Workbooks
w.Save
Next w
appXL.Application.DisplayAlerts = True
DoCmd.Quit acQuitSaveAll
Application.Quit
End sub
You are setting the DisplayAlerts to the Application's Applicaiton
appXL.Application.DisplayAlerts = True
is conceptually equivalent to
Excel.Application.Application.DisplayAlerts = True
So the property is being set on the parent application to Excel.
Try
appXL.DisplayAlerts = True
After writing ,when i'm trying to close the excel, it is not giving
any alerts like Do you want to save the contents?
As #David Zemens says, why would it display a message to save all changes when you've already saved everything. Have you tried changing a cell and then exiting Excel?
After an extensive search I have been unable to find any information on this that I could understand. there are numerous examples, but these are all for access 2003, and these do not work in access 2010.
I need to run a vba code that will export the results of a query (QryTotalSale) to excel 2010 and automatically create a bar chart of the data and show this over the database that is running.
If anyone could give me some advise then I would greatly appreciate it, or even a link to a valid resource that will work in 2010.
So far I can get excel to open, and display the results of the query in question.
To make it more difficult I really need the query to open a specific excel file, which will be on a folder on the desktop and every time the button is pressed to run the VBA, a new page should be added to the excel workbook, and the new graph be shown, and saved into the spreadsheet, so that at a later date the entire excel file can be viewed.
I have the below code, but it does not work. the bit about ranges would work in excel, but access does not seem to recognise range ( which does not really suprise me as it does not really work with ranges to my knowledge.)
My second thought was to have the first two doCmd's run, then have the next bit be forced to auto run in the excel file.
Private Sub SalesImage_Click()
DoCmd.OpenQuery "QryTotalSale"
DoCmd.RunCommand acCmdOutputToExcel
Dim myRange as range
Set myRange = B2 * C30
Charts.Add
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=myRange, _
PlotBy:=xlColumns
ActiveChart.Location Where:=xlLocationAsNewSheet
End Sub
I found a adodb code type thing for the 2003 versions of access and excel, but could not get this to work. half of the options no longer seem to be recognised by access...
I am a long way off and would really appreciate any help.
Thanks
Sam
Here are some notes. I have used late binding, so you do not need to set a reference to the Excel library, however, I have included notes on the types.
Dim xl As Object ''Excel.Application
Dim wb As Object ''Excel.Workbook
Dim ws As Object ''Excel.Worksheet
Dim ch As Object ''Excel.Chart
Dim myRange As Object
Set xl = CreateObject("Excel.Application")
sExcelWB = "z:\docs\testchart.xls"
''This will overwrite any previous run of this query to this workbook
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Query1", _
sExcelWB, True
Set wb = xl.Workbooks.Open(sExcelWB)
''Sheets are named with the Access query name
Set ws = wb.Sheets("Query1")
Set ch = xl.Charts.Add
ch.ChartType = xlColumnClustered
xl.Visible = True
xl.UserControl = True
''Still not saved
I have a table in MS Access, which has the following data to be exported to excel
Release numbers
Test cases
Results
After exporting to Excel I want to have distinct release numbers as rows starting from A2 and distinct test case name as columns starting from B1. There might be couple thousands records. Then each cell will be set to result tag. Additionally will need some fancy coloring/bordering stuff.
The question - is it possible to do this using VBA in Access and if yes what is the way to go? Any hint, sample, example, resource would be appreciated... I've googled but the most thing I came accross is DoCmd.TransferSpreadsheet or DoCmd.OutputTo which I believe will not do what I want. Saw some examples with CreateObject("Excel.Application") but not sure what are limitations and performance using this way.
I don't know if it would work for your case, but you might try adding the VBA code to an Excel document rather than the Access database. Then you could refresh the data from the Excel file and add the formatting there much easier. Here is one example:
http://www.exceltip.com/st/Import_data_from_Access_to_Excel_%28ADO%29_using_VBA_in_Microsoft_Excel/427.html
(Or see other examples at http://www.exceltip.com/exceltips.php?view=category&ID=213)
Again, it may not work for your case, but it may be an option to consider. Essentially, instead of pushing from Access, you would pull from Excel.
Yes, there are many cases when the DoCmd.TransferSpreadsheet command is inadaquate.
The easiest way is to reference the Excel xx.x Object model within Access (Early Binding). Create and test your vba export function that way. Then once you are satisfied with your output, remove the Excel object model reference, then change your objects to use use Late Binding using CreateObject. This allows you to easily have other machines that are using different versions of Excel/Access to use it just the same.
Here is a quick example:
Sub ExportRecordsetToExcel(outputPath As String, rs As ADODB.Recordset)
'exports the past due report in correct formattig to the specified path
On Error GoTo handler:
Const xlUP As Long = -4162 'excel constants if used need to be referenced manually!
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim row As Long
If rs.BOF And rs.EOF Then
Exit Sub 'no data to write
Else
rs.MoveFirst
End If
row = 1
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = False 'toggle for debugging
Set oBook = oExcel.Workbooks.Add 'default workbook has 3 sheets
'Add data to cells of the first worksheet in the new workbook.
Set oSheet = oBook.worksheets(1)
Do While rs.EOF = False
oSheet.range("A" & row).value = rs.Fields("MyField").value
'increase row
row = row + 1
Loop
oBook.SaveAs (outputPath)
'tidy up, dont leave open excel process
Set oSheet = Nothing
Set oBook = Nothing
oExcel.Quit
Set oExcel = Nothing
Exit Sub
handler:
'clean up all objects to not leave hanging processes
End Sub