Writing to an external file using ACCESS 97 - ms-access

I'm using classic VBA and I'm having problems creating an external file.
Bassically using a table I want to create a standard txt file.
I already found a way to check if the file exists and kill it.
If Dir("%USERPROFILE%\Documents\iMacros\Macros\CriarGDC.iim") <> "" Then
Kill "%USERPROFILE%\Documents\iMacros\Macros\CriarGDC.iim"
Else
End If
and also a way to write all the lines I need
Open "%USERPROFILE%\Documents\iMacros\Macros\CriarGDC.iim" For Append As #1
Print #1, "1100258698,4"
Close #1
and also found a way to launch firefox with the imacros file
Problem IS:
I CANNOT CREATE the file.
I tried using
Shell ("cmd.exe")
SendKeys ("dir /s/b %USERPROFILE%\Documents\iMacros\Macros\*.itwontfindanything > %USERPROFILE%\Documents\iMacros\Macros\CriarGDC.iim")
But I'm having some permissions problems - windows 7 won't allow me to do that.
A lot of people told me that the command
Sub WriteFile(ByVal FileName As String, ByVal Contexto As String)
Dim fnum%
fnum = FreeFile()
Open FileName For Output As fnum
Print #fnum, Contexto
Close #fnum
End Sub
Should work, but it just doesn't!
Erm...
Help.

When giving your WriteFile procedure a FileName which includes an environment variable (such as "%USERPROFILE%\Documents\foo.txt"), VBA gives me error #76, 'Path not found".
Use the Environ() function to resolve your environment variable before you give it to WriteFile.
WriteFile Environ("USERPROFILE") & "\Documents\iMacros\Macros\CriarGDC.iim", "some text"

Related

Access VBA Macro to run pass through query

I have a pass through query built in Teradata set to export data to an Excel spreadsheet. I'm trying to automate it, but when I run the macro or open the query, a window pops up asking for the data source. I have an ODBC connection created and I'm thinking there has to be a way to make the macro pass the data source name so it will run without interaction.
Edit: Adding Macro as requested
Function AutoExec()
On Error GoTo AutoExec_Err
DoCmd.OutputTo acOutputQuery, "Performance Interval Data", "ExcelWorkbook(*.xlsx)", _
"filepath\filename.xlsx", False, "", , acExportQualityPrint
DoCmd.Quit acExit
AutoExec_Exit:
Exit Function
AutoExec_Err:
MsgBox Error$
Resume AutoExec_Exit
End Function
Couple of concerns, (can't validate any of this right now as I do not currently have access to Access for testing), but it looks like:
You're trying to OutputTo a query, to the best of my knowledge that
is not feasible.
Your file path is setup as filepath\filename.xlsx unless that is the actual location and name of your Excel sheet, something seems
wrong there to me.
I don't really think this macro relates to an ODBC of any sort in its current state.
But, you should at least start with fixing the filepath issue. That should be the full path to your Excel file and the full name of the file as well. (i.e. C:\TEMP\TestExcelSheet.xlsx)
All that being said, you may want to just go with something like this (although its a little difficult to tell if this is what you actually want or not):
'Export Excel file from Query
DoCmd.TransferSpreadsheet acExport, , "acOutputQuery", _
"C:\TEMP\TestExcelSheet.xlsx", True
NOTE: "acOutputQuery" should be the actual name of your passthrough query, "C:\TEMP\TestExcelSheet.xlsx" would be your destination path, and True adds the query's headers into the sheet, False to ignore the headers.

MSAccess - TransferDatabase - File locked open?

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.

Vb.Net (Visual basic), Web Browser Control; make an external file available to pages

I've been developing an "IDE" for custom software that relies on a web browser control to display it's information. The software uses an external file "common.vbs" to access common functions within it's web pages. Sprinkled throughout various web pages within the application is the html tag:
<script LANGUAGE="VBScript" src="common.vbs"></script>
In my application I've tried the following code after importing the code into a resource string:
Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
sPath = Path.Combine(sPath, "common.vbs")
Try
Dim fs As FileStream = File.Create(sPath)
Dim sData As String = My.Resources.common
Dim Info As Byte() = New UTF8Encoding(True).GetBytes(My.Resources.common)
fs.Write(Info, 0, Info.Length)
fs.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
The code doesn't error. When I test (withing the same function) reading the file back, it's contents are returned; I know the file is being written, but when the any of the pages load with the above HTML tags, I get an error from the page:
An error has occurred in the script on this page
Line: 0
Char: 0
Error: Script error
Code: 0
URL: about:common.vbs
The file I'm trying to "include" contains only functions like:
Function DoHelp
window.external.DoHelp "", "", -1, -1
End Function
Function SQLDate( d)
SQLDate = "'" & DatePart("yyyy", d) & "-" & DatePart("m", d) & "-" & DatePart("d", d) & "'"
End Function
Function MonitorJob( jobId)
on error resume next
window.external.UIControl.MonitorJob jobId, 0
End Function
Within the application, there are no problems loading and using any of the functions contained within the file. The actual contents of the file is from the application and hasn't been edited in any manor. Any page that I load with my application that has the file included errors out, including simple test pages.
Does anyone have any ideas on how to get the web browsers control recognize a file from within a script's scr tag that's not part of the actual page being loaded and supplied from the hosting application? Editing all of the pages within the source application really isn't an option; may are dynamically created and there is a large number of them.
I've tried to include as much information as I can here, but if you need more info, please feel free to ask!
Thanks, Fred
EDIT / UPDATE:
I've tried writing all of the files I need to "include" into a temp folder, write the calling HTML file to the same folder, then load the web control using a file stream. The results are the same.
EDIT / UPDATE
I must have things wrong; Writing all of the "resource Files" into the temp folder, then writing the resulting HTML page into the same file and finally calling the Navigate method to that temp folder and file results in the page properly loading images and the underlying included VBS file.
Last EDIT / UPDATE
It took me a while to get all of the parts working correctly. Below is the answer that solved the issue.
Part of the problem is how the web control is loaded. Using the document methods circumvents accessing the file system because no base location is used. In order to access items in the file system, the "source page" needs to be in the file system. The next part of the problem was getting the resources into the file system. Below is the code that I used. Important note: for demonstration reasons only, the code for the Temp Path is located inside this routine. It actually resides out side the routine for access in other routines.
Sub UpdateFiles(sData)
'Write all the dependent files into the working folder.
Dim sLocalPath As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
Do While Directory.Exists(TempWorkingPath) Or File.Exists(TempWorkingPath)
sLocalPath = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
Loop
Directory.CreateDirectory(sLocalPath)
File.WriteAllBytes(Path.Combine(sLocalPath, "common.vbs"), System.Text.Encoding.UTF32.GetBytes(My.Resources.common))
Dim aImageList() As String = Split(My.Resources.M3ImageList, vbCrLf)
Dim sImageList As String = Replace(Join(Split(My.Resources.M3ImageList, vbCrLf), ","), "-", "_")
Dim ResourceSet As Resources.ResourceSet = My.Resources.ResourceManager.GetResourceSet(Globalization.CultureInfo.CurrentCulture, True, True)
For Each Dict As DictionaryEntry In ResourceSet.OfType(Of Object)()
If TypeOf (Dict.Value) Is Drawing.Image Then
If InStr(sImageList, Dict.Key, vbTextCompare) > 0 Then
Dim ImageConverter As New ImageConverter
Dim aBytes() As Byte = ImageConverter.ConvertTo(Dict.Value, GetType(Byte()))
Dim sName As String = Replace(Dict.Key.ToString & ".gif", "_", "-")
File.WriteAllBytes(Path.Combine(sLocalPath, sName), aBytes)
End If
End If
Next
File.WriteAllText(Path.Combine(sLocalPath, "index.html"), sData)
End Sub
I used a separate resource file that listed all of the files I needed to drive this routine. One point of note, when I imported all of the GIF's, the -'s were converted into _'s, thus the replace statements. I also used a filter (the Instr command) so that only the items in the list were exported.
I spent a lot of time on this, and I hope others will find it useful!
Fred

File Dialog error access VBA

I am trying to have the file dialog box pop up so the user can select a file path to export a file in VBA but for some reason it throws this error on the following line of code.
Error: Method 'FileDialog' of object '_Application' failed
Code: longResult = Application.FileDialog(msoFileDialogFolderPicker).Show
All Code:
If choice = 6 Then
Dim intResult As Long
Dim strPath As String
'the dialog is displayed to the user
longResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
'dispaly message box
Call MsgBox(Application.FileDialog(msoFileDialogFolderPicker _
).SelectedItems(1), vbInformation, "Selected Folder")
End If
Else
End
End If
I am really unsure how to fix this issue. I checked my syntax and everything.
I know that this is a bit of an old question at this point, but since it doesn't actually have the answer, and I needed one today, I'm going to chime in with what I found just in case anyone else needs the answer too.
To fix this you need to add a reference to "Microsoft Office [yourversion] Object Library" in Visual Basic Editor >> Tools >> References...
The dialog in question should look like this:
Was trying to do the same thing myself and found this question. I realize that it is over a year old.
Try using the actual number (4) instead of msoFileDialogFolderPicker, that worked for me. I think something needs to be installed for the msoFileDialog constants to be initialized, when I tried printing any of the constants defined in the help file in the immediate window nothing was printed.
Also, why does your code have one variable longResult and one variable intResult?
Almost nothing is an integer in VB6 as integer is a VB4 16 bit type. Win32 Integers are called Long in VB6/VBA.
This was to make porting 16 bit code to 32 bit easy.
Check out http://msdn.microsoft.com/en-us/library/office/ff865217%28v=office.15%29.aspx for more information on proper syntax with FileDialogue.Show method. It appears you need a Set in front of your variable.
If you are after some cool UI, you can checkout my Github for sample database using .NET wrapper dll. Which allows you to simply call a function and to open filedialog with file-drag-and-drop function
Dim FilePaths As String
FilePaths = gDll.DLL.ShowDialogForFile("No multiple files allowed", False)
'Will return a JSONArray string.
'Multiple files can be opend by setting AllowMulti:=true
here what it looks like;

VBS file only works when double-clicked

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")