msaccess - storing sql query in external file - sql

I dislike the built in text editor for MsAccess and would like to use an external text editor.
Expanding on a previous question: msaccess - sql view - autocomplete / intellisense or alternate way to write queries?
Is there a way I can store the sql query in an external file and have MsAccess reference it?

If you are OK with setting the recordsource via VBA, then you can use this:
Public Function ReadTxt(filePath As String) As String
Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
Dim oFS As TextStream
If oFSO.FileExists(filePath) Then
On Error GoTo Err
Set oFS = oFSO.OpenTextFile(filePath)
' read file
ReadTxt = oFS.ReadAll
'Debug.Print IIf(oFS Is Nothing, "file is closed", "file opened")
oFS.Close
Else
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Function
End If
Exit Function
Err:
MsgBox "Error while reading the file.", vbCritical, vbNullString
oFS.Close
Exit Function
End Function
Usage: ReadTxt("C:\TempFolder\YourQuery.txt")
However, it's a lot of fiddling around, why not just cut and paste it (the SQL) into Access?

Related

MS Access: Upload multiple files from one button

I am trying to upload multiple files at once into an access database via the use of a button. However only one file will upload at a time.
When the button is clicked it calls a sub procedure. My code is below:
Private Sub btnImport_Click()
'Calls the procdure that imports raw files
Call Module1.ImportRawFiles
End Sub
Public Sub ImportRawFiles()
Dim oFileDiag As Office.FileDialog
Dim path As String: path = ""
Dim oFSO As New FileSystemObject
Dim FileSelected As Variant
Set oFileDiag = Application.FileDialog(msoFileDialogFilePicker) ''Picks file to import
oFileDiag.AllowMultiSelect = True ''Allows multiple files to be selected
oFileDiag.Title = "Please select the reports to upload"
oFileDiag.Filters.Clear
oFileDiag.Filters.Add "Excel Spreadsheets", "*.xlsx, *.xls" ''Only allows xlsx and xls file types to upload
If oFileDiag.Show Then
For Each FileSelected In oFileDiag.SelectedItems
Form_Homepage.txtFileName = FileSelected
Next
End If
If Nz(Form_Homepage.txtFileName, "") = "" Then
MsgBox "No files selected please select a file"
Exit Sub
End If
If oFileDiag.SelectedItems.Count > 0 Then path = oFileDiag.SelectedItems(1)
If Len(path) > 0 Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, oFSO.GetFileName(Form_Homepage.txtFileName), path, 1
MsgBox "The " & oFSO.GetFileName(Form_Homepage.txtFileName) & " file has been uploaded"
Else
MsgBox "File not found"
End If
Does anyone know why only one file is uploading?
You are looping through all selected files to assign Form_Homepage.txtFileName but then not doing anything else in that same loop:
If oFileDiag.Show Then
For Each FileSelected In oFileDiag.SelectedItems
Form_Homepage.txtFileName = FileSelected
Next
End If
So by end of the loop, the last selected file is assigned, ignoring all the others, then your later logic statements only perform on that one file.
One solution would be to move your action logic up to the same loop. So move your IF statements into the assignment loop, that way they operate on each iterative assignment of your variable.

Access VB export certain query to designated filepath

So I have a query named "the query I wish to export", I want to be able to export the query to Excel when I click the button on my form.
I created this function in Module1 to call the dialog out and determine which file path I want to save my query result to.
Public Function ExportToExcel(strQuery As String)
On Error GoTo Err_Handler
Const MESSAGETEXT = "Overwrite existing file?"
Dim OpenDlg As New BrowseForFileClass
Dim strPath As String
OpenDlg.DialogTitle = "Enter or Select File"
strPath = OpenDlg.GetFileSpec
Set OpenDlg = Nothing
If strPath <> "" Then
If Dir(strPath) <> "" Then
If MsgBox(MESSAGETEXT, vbQuestion + vbYesNo, "Confirm") = vbNo Then
Exit Function
Else
Kill strPath
End If
End If
Else
Exit Function
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, strQuery, strPath
Exit_Here:
Exit Sub
Err_Handler:
MsgBox Err.Description
Resume Exit_Here
End Function
After complete this function, I call this function and wish to export my query to the filepath that I wish to select.
Private Sub Export1_Click()
Call Module1.ExportToExcel "the query I wish to export"
End Sub
It just keeps giving me "Syntax Error". I don't really understand because I specifically call the function, passing the query name as its argument, any ideas?
Since you're evaluating the function using the Call keyword (which isn't strictly required), the arguments will need to be enclosed in parentheses, i.e.:
Call Module1.ExportToExcel("the query I wish to export")
For the file selection/specification, I would suggest using the FileDialog object, which will require a reference to the Microsoft Office ##.0 Object Library.
To provide an example of how this may be implemented, below is a quick function to demonstrate how you might go about prompting the user to specify/select an Excel file:
Function GetExcelFile(msg As String) As String
Dim dia As FileDialog
Set dia = Application.FileDialog(msoFileDialogFilePicker)
With dia
.AllowMultiSelect = False
.Title = msg
.Filters.Clear
.Filters.Add "Excel Files", "*.xls; *.xlsx"
If .show Then
GetExcelFile = .SelectedItems.Item(1)
End If
End With
End Function
Call the above with the desired dialog title, e.g.:
GetExcelFile "Enter or Select File"
The above will return an empty string if the user presses Cancel when prompted.

VBA excel: how to add text to all files on a folder

I need to add text string to all files on a folder, as a footer
For example, on the folder on the path and called C:\mobatchscripts\
I have a random number of txt files, with text.
I want to add a line for example "text" on each of the text files on the folder
I have little knowledge of vba programming, but for what I have read I can use append, but I need something that loop on the files on the folder, and modify them.
So far I tried this:
Sub footer()
Dim FolderPath As String
Dim FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\mobatchscripts\"
FileName = Dir(FolderPath)
Do While FileName <> ""
Open FileName For Append As #1
Print #1, "test"
Close #1
FileName = Dir
Loop
End Sub
But seems that its not looking into the files, or appending the text.
On the assumption that you're writing to text files (I see "batchscripts" in the path), you need a reference to the Microsoft Scripting Runtime (Within the VBE you'll find it in Tools, References)
Option Explicit
Public Sub AppendTextToFiles(strFolderPath As String, _
strAppendText As String, _
blnAddLine As Boolean)
Dim objFSO As FileSystemObject
Dim fldOutput As Folder
Dim filCurrent As File
Dim txsOutput As TextStream
Set objFSO = New FileSystemObject
If objFSO.FolderExists(strFolderPath) Then
Set fldOutput = objFSO.GetFolder(strFolderPath)
For Each filCurrent In fldOutput.Files
Set txsOutput = filCurrent.OpenAsTextStream(ForAppending)
If blnAddLine Then
txsOutput.WriteLine strAppendText
Else
txsOutput.Write strAppendText
End If
txsOutput.Close
Next
MsgBox "Wrote text to " & fldOutput.Files.Count & " files", vbInformation
Else
MsgBox "Path not found", vbExclamation, "Invalid path"
End If
End Sub
I'd recommend adding error handling as well and possibly a check for the file extension to ensure that you're writing only to those files that you want to.
To add a line it would be called like this:
AppendTextToFiles "C:\mobatchscripts", "Test", True
To just add text to the file - no new line:
AppendTextToFiles "C:\mobatchscripts", "Test", False
Alternatively, forget the params and convert them to constants at the beginning of the proc. Next time I'd recommend working on the wording of your question as it's not really very clear what you're trying to achieve.

VBA Dir function not working on Excel 2010

I mapped an intranet location using the File Explorer. i.e. mapped http://intranet.XXXXXXX.com/mydir/ to M:\
I'm using the Dir function to test if a file is present in that location:
Dim FileExists as Boolean
FileExists = Dir("M:\myfile") <> ""
If FileExists Then MsgBox "File found in M:"
I run that macro on Excel 2007 and it Works Fine. When I run it on Excel 2010 though, Dir("M:\myfile") always returns "", even if the file is present in the specified location. I canĀ“t find a solution that will work on both Excel versions. Any ideas?
You may add file extension as a wildcard character at the end of filepath. I gave a try in excel 2010 and it worked for me.
Dim FileExists As Boolean
FileExists = Dir("D:\myfile" & "*.txt") <> ""
If FileExists Then MsgBox "File found in M:"
I found that if I use the full network name, it works first go. This wasn't just in VBA, but also some shortcuts also - they returned "File could not be found".
Changing from the mapped shortcut, e.g.
Y:\Projects\Proj1\File1.xlsx
to the full mapped path, e.g.
\\server\Department\Projects\Proj1\File1.xlsx
Fixed the problem
Here is how to use FSO to do what you want:
Option Explicit
Function test_it()
'Test the Function - must pass the file path and name
Debug.Print Does_File_Exist("C:\temp\form1.txt")
End Function
Private Function Does_File_Exist(sFullPath) As Boolean
' Will return True or False if file exists.
' Provide the fully qualified path and file name.
' You can disable the MsgBox displays after testing
Dim oFs As New FileSystemObject
Dim oFile As File
Set oFs = New FileSystemObject
If oFs.FileExists(sFullPath) Then
Does_File_Exist = True
MsgBox "Found file: " & sFullPath
Else
Does_File_Exist = False
MsgBox "File not found: " & sFullPath
End If
Set oFs = Nothing
End Function

Delete all files within a directory vb6

I was wondering if anyone could help me with a vb6 function that would delete all files within a directory (excluding subdirectories).
One line, using the VB6 statement Kill
Kill "c:\doomed_dir\*.*"
The help topic says "In Microsoft Windows, Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files".
As an aside - I prefer to avoid the Microsoft Scripting Runtime (including FileSystemObject). In my experience it's occasionally broken on user machines, perhaps because their IT department are paranoid about viruses.
I believe this should work:
Dim oFs As New FileSystemObject
Dim oFolder As Folder
Dim oFile As File
If oFs.FolderExists(FolderSpec) Then
Set oFolder = oFs.GetFolder(FolderSpec)
'caution!
On Error Resume Next
For Each oFile In oFolder.Files
oFile.Delete True 'setting force to true will delete a read-only file
Next
DeleteAllFiles = oFolder.Files.Count = 0
End If
End Function
I haven't tested every scenario but it should work. It should delete every file and if the file is locked or you don't have access you should get Error 70 which is caught and you get an Abort, Retry or Ignore box.
Sub DeleteAllFilesInDir(ByVal pathName As String)
On Error GoTo errorHandler
Dim fileName As String
If Len(pathName) > 0 Then
If Right(pathName, 1) <> "\" Then pathName = pathName & "\"
End If
fileName = Dir(pathName & "*")
While Len(fileName) > 0
Kill pathName & fileName
fileName = Dir()
Wend
Exit Sub
errorHandler:
If Err.Number = 70 Then
Select Case MsgBox("Could not delete " & fileName & ". Permission denied. File may be open by another user or otherwise locked.", vbAbortRetryIgnore, "Unable to Delete File")
Case vbAbort:
Exit Sub
Case vbIgnore:
Resume Next
Case vbRetry:
Resume
End Select
Else
MsgBox "Error deleting file " & fileName & ".", vbOKOnly Or vbCritical, "Error Deleting File"
End If
End Sub
It would seem that the Scripting runtime FileSystemObject's DeleteFile method also supports wildcards as this works for me:
Dim fs As New Scripting.FileSystemObject
fs.Deletefile "C:\Temp\*.jpg", true
This approach has less control than the approach suggested by #Corazu, but may have some utility in certain cases.