Trying to Open a File with a Button from Access using ShellExecute - vba

In my Access database, I have a button on a form to open an external file.
Here is the code that I am using for that.
Private Sub btn_OpenFile_Click()
Dim a As New Shell32.Shell
Dim strPath As String
strPath = Me.Attachment
strPath = Chr(34) & strPath & Chr(34)
Call a.ShellExecute(Me.Attachment)
'Call CreateObject("Shell.Application").ShellExecute(strPath)
'MsgBox strPath
End Sub
The problem that I have is if I actually put in the value of the variable (Me.Attachment) it works fine and opens the program and the file.
For Example, If I put in Call a.ShellExecute("C:\Docs\Some File.pdf") it will open. But if I use the variable in it's place it won't open and tells me it cannot find the file. I have verified with the msgbox that it is receiving the correct information. I have tried to wrap it in quotes and have used the Chr(34) as shown above but nothing works.
How can I get that variable to work in the ShellExcute command?
I have looked through all the forums and it seems like everyone is using a string but not a variable. I don't want to use just the shell command as I don't want to track down all of the different apps people use to open different types of files. There will be different file types that will need to be opened and I thought this would be easier than it actually is.
Thank you for the help.

I'm pretty sure that ShellExecute expects a Variant parameter, not a String.
So try this:
Call a.ShellExecute(CVar(strPath))
or use a Variant variable from the start.
I had the same problem here.

Both of the following work for me:
Dim a As New Shell32.Shell
Dim strPath As String
strPath = Me.Attachment
Call a.ShellExecute(strPath)
Dim a As Shell
Dim strPath As String
strPath = Me.Attachment
Set a = CreateObject("Shell.Application")
a.ShellExecute strPath
Even referencing Attachment directly.
a.ShellExecute(Me.Attachment)

Related

Move folders in network location using Access VBA

I want to move folders which are on network using Access VBA.
When I click button on form, it shall execute VBA code.
The below program moves local PC folders, when \\?\ is removed from the code. Using \\?\ before any network folder path, it is creating new folder on network.
When I want to move folders it is giving:
Run time Error 5 : Invalid Procedure call or Argument.
Upon debug , it highlights objF.MoveFolder oldStr, newStr
Private Sub btnBrowse_Click()
Dim oldStr As String
Dim newStr As String
Dim objF As Object
Me.OldPath = Me.FolderPath
Me.NewPath = GetFolder()
If Len(Me.NewPath) > 0 Then
Me.NewPath = "\\?\" & Me.NewPath
Me.FolderPath = Me.NewPath
Set objF = CreateObject("Scripting.FileSystemObject")
oldStr = Me.OldPath & "\*"
newStr = Me.NewPath & "\"
objF.MoveFolder oldStr, newStr
End If
End Sub
Use Microsoft.Scripting.Runtime file object to move folder.
We can't use these \\?\ paths. Should use conventional paths. \\?\ has noting to do with networks. Networks are \\servername\sharename\folder\file.ext
I removed \\?\ and it was working all good. \\?\ was creating confusion to MS Access in recognizing path, & thus was throwing error.

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

Access vba Check if file exists

I have a database split in FrontEnd and BackEnd.
I have it running:
i) in my office
ii) updating/testing in my personal computer.
My BackEnd file is running in different Folder location according to computer running.
I want to place a code and check if file exist.
Code:
Sub FileExists()
Dim strPath As String '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String '<== Admin.
strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"
If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
If Dir(strPathAdmin & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
Else
'===> Office User.
If Dir(strPath & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
End If
End Sub()
I have this until now.
Any help.
Thank you...
Create a small function to check if a file exists and call it when needed.
Public Function FileExists(ByVal path_ As String) As Boolean
FileExists = (Len(Dir(path_)) > 0)
End Function
Since the backend database paths dont change, why dont you declare two constants and simply check their value?
Sub Exist()
Const workFolder As String = "C:\Work Folder\backend.accdb"
Const personalFolder As String = "D:\Personal Folder\backend.accdb"
If FileExists(workFolder) Then
'Work folder exists
End If
'....
If FileExists(personalFolder) Then
'Personal folder exists
End If
End Sub
This is a very belated reply, but don't reinvent the wheel. VBA can access the FileSystemObject, which includes a powerful set of methods that fetch file and folder information without requiring you to write your own functions, and the resulting code is much easier to read.
Second, borrowing on the previous answer, you know the folders you want the code to look at, and they don't change much, but because they could, I would also move your parameters into the declaration so they can be customized if needed or default to existing values.
Finally, FileExists is a verb, which should scream Function rather than Sub, so I'm guessing you want to return something and use it elsewhere in higher level code. It so happens that FileExists is already the name of a method in FileSystemObject, so I'm going to rename your function to LocatePath. You could return the valid path of the file you're looking for and decide by convention to quietly return an empty string "" if the target isn't found, and handle that in the calling procedure.
fs.BuildPath(strRootPath, strFileOrSubDir) appends strFileOrSubDir to strRootPath to construct a properly
formatted, full pathname and you don't need to worry about
whether you have backslashes (or too many) between the two.
It can be used to append files, or subdirectories, or
files in subdirectories.
fs.FileExists(strFullPath) is simple, returns True if strFullPath exists,
and False otherwise.
fs.GetFolder(strFolderName) returns a Folder object that has a
.Files property, which is a Collection object. Collection
objects in turn have a .Count property, which in this example
indicates how many files are in strFolderName. The Collection
object could also be used to iterate over all the files in the
folder individually.
What follows is your code refactored to incorporate all the changes I recommend according to what I think you're trying to achieve. It's not as symmetric as I'd like, but mirrors your code, and it's simple, easy to read, and finished in the sense that it does something.
Function LocatePath(Optional strWorkPath as String = "\\iMac",
Optional strHomePath as String = CurrentProject.Path,
Optional strFile as String = "SerialKey.txt"
Optional strSubDir as String = "Temp") as String
Dim fs as Object
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(fs.BuildPath(strHomePath, strFile)) Then
If fs.GetFolder(fs.BuildPath(strHomePath, strSubDir).Files.Count > 0 Then '===> Admin User.
LocatePath = fs.BuildPath(strHomePath, strFile)
ElseIf fs.GetFolder(fs.BuildPath(strWorkPath, strSubDir).Files.Count > 0 Then '===> Office User
LocatePath = fs.BuildPath(strWorkPath, strFile)
End If
Else 'Target conditions not found
LocatePath = ""
End If
Set fs = Nothing
End Function()
Ideally, I probably wouldn't specify strHomePath as String = CurrentProject.Path because strWorkPath as String = CurrentProject.Path is probably also true when you're at work, and you would want to do a better job of differentiating between the two environments. This is also what causes the little problem with symmetry that I mentioned.

Convert multiple .xls files to .xlsx in ssis

I have a folder that receives multiple excel files in .xls format. I need to change the format type to .xlsx in order to load the excel data into SQLvia SSIS. I know how to rename the file using "File System Task" but that works for a specific file. but my file contains a file # and date as well that needs to stay same as source file, I only want the file type to change and the file move to a processed folder. Can anyone help me?
Source Path: C:\Documents\TestFolder
Source File: TestSegRpt_0001_2017_02_22.xls
Destination Path: C:\Documents\TestFolderProcessed
Destination File: TestSegRpt_0001_2017_02_22.xlsx
Hoping i understood your problem correctly.
I think below link will help.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-mso_other/batch-convert-xls-to-xlsx/1d9b3d78-daf0-4014-8fb2-930aca6493b0
You have to add a Script Task, loop over files, and use a function like the following to create precessed directory and convert files (code in Vb.net):
Public Sub ConvertXlsToXlsx(ByVal strpath as string)
Dim strDirectory as string = System.IO.Path.GetDirectoryName(strpath) & "Processed"
If Not System.IO.Directory.Exists(strDirectory) Then System.IO.Directory.CreateDirectory(strDirectory)
Dim xl As New Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
xlWorkBook = xl.Workbooks.Open(strpath)
xlBook.SaveAs(strDirectory & "\" & System.IO.Path.GetFilename(strpath) & "x")
xl.Application.Workbooks.Close()
xl.Application.Quit()
End Sub
Your code will look like:
Public Sub Main
Dim strFolder as string = Dts.Variables.Item("FolderPath").Value
Dim strXlsFiles() as string = IO.Directory.GetFiles(strFolder,"*.xlsx",SearchOption.TopDirectoryOnly)
For each strFile as String in strXlsFiles
If strFile.EndsWith("xlsx") The Continue For
ConvertXlsToXlsx(strFile)
Next
End Sub
Reference:
https://social.msdn.microsoft.com/Forums/office/en-US/a73f846c-91ee-4dad-bd7b-c04d418d0561/convert-xls-into-xlsx?forum=exceldev

Screenshot window and save with environment variables

I have code to take a screenshot of a window, seen here:
SC.CaptureWindowToFile(Me.Handle, "c:\Program Files\image_" & Now.ToString("yyyyMMddHHmmss") & ".png", Imaging.ImageFormat.Png)
I want to be able to set an environment variable so that the images will be saved in a folder created by my installer, let's call it "Screenshots" and it's in the Documents folder. I assume I'll have to use something like:
Dim fullPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
But I don't know how to combine these two together so it will save the screenshots into the folder in my documents. Any ideas?
If I understand your question, this should do it:
Dim myDocumentsPath as String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim formattedDateString as String = Date.Now.ToString("yyyyMMddHHmmss")
Dim imagePath as String = String.Format("{0}\Screenshots\image_{1}.png", myDocumentsPath, formattedDateString)
SC.CaptureWindowToFile(Me.Handle, imagePath, Imaging.ImageFormat.Png)