Hey there!
Im new here, well, as a member, but not as a viewer.
anyways, i am making a vb project, novice one.

i need to open a file located in d:\\Documents\\MB.accdb

now, i would be very happy if i would get the code to open the file, not in vb, but with the default viewer of the system, like when i double click on the file itself.
Thanks in advance!
Ykbks.:)

Recommended Answers

All 21 Replies

This is not really a VB question. You're in the wrong forum. Unless you want to use vb to change the registry, etc.

But in Windows Explorer choose the Tools menu>FolderOptions>File Types. Associate the extension with a program. And that's it.

yes, it is a VB question. Opening a file in its' native application is a common practice. I do it all the time.

Look here for an example - http://www.developerfusion.com/code/278/open-a-fileurl-with-its-default-program/

I use a slightly different method, but the above works ok, too.

here's my way of doing it - http://www.daniweb.com/software-development/visual-basic-4-5-6/code/383557

(m)

commented: thanks +0

Well, the request--to say the least--was confusing. I want to open the file, but not in VB?

So, you have someone asking for help in VB, but does not want to use VB? And then you give them code for doing what they request in VB.

Sigh...............

To open the file with a double click event, you must have some object that has a double click event and that is able to store file names. In the double click event, use the Shell command as so deftly posted by mb01a.

yes, it is a VB question. Opening a file in its' native application is a common practice. I do it all the time.

Look here for an example - http://www.developerfusion.com/code/278/open-a-fileurl-with-its-default-program/

I use a slightly different method, but the above works ok, too.

here's my way of doing it - http://www.daniweb.com/software-development/visual-basic-4-5-6/code/383557

(m)

Thanks.
I will try this and let you know.
This is for vb6 , right?

Sometimes what is not said is more important that what is said. Trying to describe a process to a programmer without knowing the common "programmer acronyms" can be a challenge. I usually try to read between the line and try to find what the user really wants, not what it looks like he's asking for. And often it can be done without playing '20 questions' ..

Yes, the code in both links is VB6 code. Neither codepiece is complete. You'll need to customize it to make it do what you need. The code in my link = http://www.daniweb.com/software-deve...-6/code/383557 was pulled from a production program that is able to open any file or document in its' native application. The 'native application' must be installed on the workstation so the file association can be determined. (to open pdf files, you need at least adobe reader)

Thanks man! im working on a database for a charity. i will need this to work :D i shall let you know what happens. Cheers!

Let me know if I can help further

Let me know if I can help further

ive tried this-

Private Sub Command1_Click()

If Text2 = "haqqulibad" Then
ShellExecute , vbNullString, """"D:\Documents\MB.accdb"""", vbNullString, vbNullString,vbNormalFocus
Else
Err = MsgBox("Wrong code!", vbOKOnly, "Error")
Unload Me


End Sub

and declared the private functon in the general section like shown in the first link.
but the problem is, i get syntax error;
and about your process, i dont get how would it point the program to my specific file@

You might want to reduce the number of quotation marks. And an End If would be helpful. For mb01a's code, to open the file you use the LoadUserFile function.

Basically you call the Function LoadUserFile(ByVal FN2Load As String) and hand it the full path to the file you want to load.

(like this)
Call LoadUserFile("D:\Documents\MB.accdb")

Think about it. There's a lot you can do with this ...

:)

what's a "haqqulibad" anyway? Do I need to repent?
ykbks needs to visit the microsoft website. That's where I foung the tools to create my original functions ..

hi,i cannot get the code work.
points error to opFile in following line

Call Shell(retassoc(opFile, opPath) & " " & Chr(34) & FN2Load & Chr(34), vbNormalFocus)

and message pops up

Compiler Error:
ByRef argument type mismatch

i am calling the function by

Call LoadUserFile("D:\MB.mdb")

Does it require any library refrences

Code function i am using by Mike Bonnell

Private Declare Function FindExecutable Lib "shell32" Alias "FindExecutableA" (ByVal lpFile As String, ByVal lpDirectory As String, ByVal sResult As String) As Long

Private Const MAX_PATH As Long = 260
Private Const ERROR_FILE_NO_ASSOCIATION As Long = 31
Private Const ERROR_FILE_NOT_FOUND As Long = 2
Private Const ERROR_PATH_NOT_FOUND As Long = 3
Private Const ERROR_FILE_SUCCESS As Long = 32 'my constant
Private Const ERROR_BAD_FORMAT As Long = 11


Dim mflg As Boolean
Public ActiveClientName As String


Function retassoc(fn As String, fpath As String) As String

 Dim success As Long
 Dim pos As Long
 Dim sResult As String


sResult = Space$(MAX_PATH)
    success = FindExecutable(fn, fpath, sResult)
    pos = InStr(sResult, Chr$(0))

    If pos Then

     retassoc = Left$(sResult, pos - 1)
End If
End Function

Function LoadUserFile(ByVal FN2Load As String)
On Error GoTo load_err
 ' load the file in its' native application
 
For x = Len(FN2Load) To 0 Step -1
If Mid(FN2Load, x, 1) = "\" Then
 opPath = Left(FN2Load, x) 
   opFile = Right(FN2Load, Len(FN2Load) - x)
                Exit For 
             End If 
           Next 
           Call Shell(retassoc(opFile, opPath) & " " & Chr(34) & FN2Load & Chr(34), vbNormalFocus)

           Exit Function

load_err:
 MsgBox "The file you are trying to open apparently has no program association available" & vbCrLf & "or it is a corrupted file. I can't open " & opFile, vbInformation vbInformation + vbOKOnly, "Error occured on file open" 


On Error GoTo 0
End Function

You receive the error because you are sending a value; i.e. your file name.

If the function requires a variable, then you need to send a variable that you declared in your function. When your function uses ByRef, then you need to send a variable. To get around the error and to use the function as is, just declare a variable and give it a value before sending it to the function. The function can then change the value of that variable, but it does not sound like it will. So, that function probably could have been more efficiently written by using ByVal. Unless the programmer's intent was to optionally change the value of the variable.

When you use the ShellExecute API you can just use "open", "print", or "explore" for the second parameter. In your case, you just want to use "open" for the operation. The operating system will use the program that is designated in the windows registry to open a file with that file's extension.

If you use the VB Shell function, you then must use the actual name of the program plus any parameters that may accompany the file. You need to use a space between the program name and the parameter; hence, chr$(32).

You have more options, if you use the ShellExecute API. But it's more complicated. The following example uses both the ShellExecute API and the VB Shell function. The VB Shell function just performs a limited set of the options of the ShellExecute API.

Option Explicit
Private Const SW_SHOWNORMAL = 1

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
    (ByVal hwnd As Long, ByVal lpOperation As String, _
    ByVal lpFile As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Sub Form_Load()
    Dim lngReturn As Long
    Dim dblReturn As Double
    lngReturn = LoadUserFile(Me.hwnd, "C:\Documents\My.mdb")
    If lngReturn < 33 Then
        MsgBox "Error # " & CStr(lngReturn), vbCritical, "Error"
    End If
    
    dblReturn = LoadMyFile("NotePad", vbNullString)
    
End Sub

Private Function LoadUserFile(ByVal AppHandle As Long, ByVal MyFileName As String) As Long
    LoadUserFile = ShellExecute(AppHandle, "open", MyFileName, 0, 0, SW_SHOWNORMAL)
End Function

Private Function LoadMyFile(ByVal MyProgramName As String, ByVal MyFileName As String) As Double
    On Error GoTo LoadError
    LoadMyFile = Shell(MyProgramName & Chr$(32) & MyFileName, vbNormalFocus)
    Exit Function
LoadError:
    LoadMyFile = Err.LastDllError
    MsgBox Err.Description, vbCritical, "Error"
End Function

Thanks for reply
i am still getting error with your code

error is
Compiler error:
Sub or function not defined.


i am new to vb and just want a vb comiled EXE to run MSACCESS mdb or accdb database.

I'm going to assume that everyone knows more than I do about this and keep quiet about it ...

Thanks for reply
i am still getting error with your code

error is
Compiler error:
Sub or function not defined.


i am new to vb and just want a vb comiled EXE to run MSACCESS mdb or accdb database.

It would help if you would list what sub or function was not defined. Usually the compiler stops on the function that is not defined and has it highlighted.

Don't make it too complicated.

If you want to use the Shell command, do something similar to the following: Shell "c:\Program Files\Microsoft Office\MSAccess.exe " & "c:\Documents and Settings\MyUserName\MyAccess.mdb", vbNormalFocus The Shell Function expects the program name and it expects any parameters, such as the filename, to be separated from the program name by a space.

The ShellExecute API is simpler; but you can just use the the word "open" with the second parameter, and the filename with the second parameter. But just try the Shell first: it should work.

thanks.

i have tried the code and it works.
But i am unable to generate custom error message if the database file is not presnt at required location.

that was the reason for giving preference to Error giving Codes.
is there any solution to this.

The Shell function returns the TaskID of a process. Otherwise, it returns an error. You can trap it as follows:

Public Sub Whatever(ByVal strProgram_With_Parameters as String)
    On Error GoTo Err_SHELL
    Dim dblReturn As Double
    dblReturn = Shell(strProgram_With_Parameters, vbNormalFocus)
    Exit Sub
Err_SHELL:
    MsgBox Err.Description & " Error " & Err.Number, vbCritical, "Error"
End Sub

The error is generated by access app.
MSAccess Windows open and tells that file c:\Documents and Settings\MyUserName\MyAccess.mdb is not present.

The error is generated by access app.
MSAccess Windows open and tells that file c:\Documents and Settings\MyUserName\MyAccess.mdb is not present.

That's just an example of an imaginary file name. You have to supply the correct file name that is on your system. I have no idea what your database file's name is, where it is on your hard drive, etc. You need to code in the correct file name.

I was going to stay out of this, but I see too many ways being described to do the same thing.

The code I posted earlier goes into a module. All of it. As is.

Elsewhere in a program I fill a listbox with the path information of the files I might want to open in their native application. The path information is stored in an MS Access table, or an sql server table, or a MySQL table, or whatever other place you might want to keep them.

I named my listbox "ListView1" (vb default name)

To populate the Listbox I used this. The path information is stored in an MS Access database:

Function popList()
' populates the listview control
Dim sql As String
dim x as integer
' the next line builds the sql statement and adds the user id to the where clause so each user can only see their own documents.
      sql = "select tblDocs.docName, tblDocs.docPath, tblDocs.id from tblDocs where clientid = " & getClientID(ActiveClientName)
'
            Call opnDB(Me)  ' this line just opens a connection to the database.
            Set rs = db.OpenRecordset(sql)
            ListView1.ListItems.Clear
            ListView1.View = lvwReport
            rs.MoveFirst
            x = 1
            With ListView1.ColumnHeaders
                .Clear
                .Add , , "Document Name", 4000
                .Add , , "Document Path", 7000
            End With
        
        Do Until rs.EOF = True
            With ListView1.ListItems
                .Add , , rs!docname
            End With
            rs.MoveNext
        Loop
        
        rs.Close
        Set rs = db.OpenRecordset(sql)
        Do Until rs.EOF = True
            With ListView1
                ' Add a value to the second column to the first item on the list
                .ListItems(x).SubItems(1) = rs!docpath
            End With
            rs.MoveNext
            x = x + 1
        Loop
        closdb()  ' this line just closes the connection
End Function

When a user clicks an item in the listbox, this code gets executed from the appropriate place in your program:

x = ListView1.SelectedItem.Index
    Call LoadUserFile(Me.ListView1.ListItems(x).SubItems(1))

Magically, the file that was clicked opens in its' native application.
By storing the path/file information in a database table, you can have as many entries as needed.
The listbox can handle 32k items, but if you have more than 50-100 items you should design a better way to do the lookups. I tied mine to a network user name so each user can see just their own items. There are probably better ways to do it if you have hundreds of users all storing their stuf in the same database ...

The error is generated by access app.
MSAccess Windows open and tells that file c:\Documents and Settings\MyUserName\MyAccess.mdb is not present.

To generate the error code in VB first, you must test the file in VB first. You can use the Microsoft Scripting Runtime Library and use the File System Object. You might try using the ShellExecute API. It returns error codes for File not found, file association errors, etc. I haven't tried it. But if you start using these extras such as file system object, Checking Error Codes on running the ShellExecute API, I would say your request for making a simple executable to run an access file is not really that simple. If you're a novice, as you say you are, then the best you can hope for is copying and pasting somebody else's code to accomplish your purpose. Or you're going to have to do some digging and show some personal effort to figure out what's going on and why.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.