Using VB 6
How to access the database from the other system or server?
Code
Cn.ConnectionString = "Provider=Microsoft.jet.oledb.4.0; Data Source=" & _
App.Path & "\DC-CS.MDB"
Cn.Open
I don’t want to give the connection directly in my code, I want to select a connection and *.mdb file from the other system or same system or server.
What type of control I have to use in VB for connection testing and mdb file selection from the other system or server?
First thing I want to select a connection, if connection tested, then I want to select a *.mdb file from other system or server. How can I select a connection and *.mdb file in VB 6.
Please need VB 6 Code Help
You can use the Data Link Properties dialog to define an OLE DB connection string. You can start out by predefining the Provider and other attributes, and then let the user browse for an MDB file and choose it if you have predefined Jet 4.0 as the Provider.
Once this selection has been made you can persist the connection as a .UDL (Universal Data Link) file. UDLs were what replaced DSNs a long, long time ago. I'm amazed they get so little use.
Here is some sample code that lets your program specify a UDL and a default path for the user to browse for an MDB file. If the UDL does not exist, it opens the Data Link Properties dialog so the user can choose an MDB, and lets them Test Connection from that dialog before Oking or Canceling their settings. Once it has the connection fully defined it persists it as a .UDL file and opens the Connection object.
If the UDL file exists it opens the Connection using the specs in the UDL.
The key here is the DbOpenPromptSave() function.
'Requries references to:
' Microsoft ActiveX Data Objects x Library (x >= 2.5)
' Microsoft OLE DB Service Component 1.0 Type Library
Private Function DbOpenPromptSave( _
ByVal Conn As ADODB.Connection, _
ByVal UDLPath As String, _
Optional ByVal MDBSearchStartPath As String = "") As Boolean
'Returns True if user cancels the dialog.
On Error Resume Next
GetAttr UDLPath
If Err.Number Then
'No UDL, we need to prompt the user then create one.
On Error GoTo 0
Dim dlkUDL As MSDASC.DataLinks
Set dlkUDL = New MSDASC.DataLinks
Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Persist Security Info=False;" _
& "Jet OLEDB:Engine Type=5;" _
& "Data Source=" & MDBSearchStartPath & "\;" _
& "Window Handle=" & CStr(Me.hWnd)
If Not dlkUDL.PromptEdit(Conn) Then
DbOpenPromptSave = True
Exit Function
End If
'Use a Stream as Unicode writer. Using a relative path to save
'respects the Current Directory of the process.
Dim stmUDL As ADODB.Stream
Set stmUDL = New ADODB.Stream
With stmUDL
.Open
.Type = adTypeText
.Charset = "unicode"
.WriteText "[oledb]", adWriteLine
.WriteText "; Everything after this line is an OLE DB initstring", _
adWriteLine
.WriteText Conn.ConnectionString
.SaveToFile UDLPath, adSaveCreateOverWrite
.Close
End With
Conn.Open
Else
Conn.Open "File Name=" & UDLPath
End If
End Function
Private Function DbActions() As Boolean
'Returns True on cancel.
Dim connDB As ADODB.Connection
Set connDB = New ADODB.Connection
If DbOpenPromptSave(connDB, "sample.udl", App.Path) Then
MsgBox "User canceled!"
DbActions = True
Exit Function
End If
DoDbOperations connDB 'Whatever you need to do until closing.
connDB.Close
End Function
The DbActions() function is simply an example of calling DbOpenPromptSave() to open the database. This function opens the database, calls DoDbOperations() (not shown) to actually work with the open database, and then closes the database Connection.
This example uses a relative path (current directory, usually the same as App.Path) for sample.udl and sets the MDBSearchStartPath (where the Select Access database dialog opens) to App.Path (because this dialog defaults to where the last CommonDialog had been opened).
So in other words...
It looks for/saves the UDL sample.udl in CD (usually App.Path), and the MDB selection dialog opens in App.Path. Whew.
I suppose just passing CurDir$() might have been clearer in this case.
I hope this comes close to what you were requesting, it was a little vague.
The MDB selection subdialog the user opens is pretty much a standard CommonDialog.ShowOpen dialog. The user should be able to browse for the MDB file on any drive including file shares on remote systems.
RBarry is referring to the fact that you can "share" a particular folder on one computer, so that it is accessible to another computer.
If two computers are named computer1 and computer2, then computer2 can share a folder on it's C: drive giving it some name like "sharedfolder". Then computer1 can access that folder using the path "\\computer2\sharedfolder".
If an application on computer1 can't use that path, then you can "map" a drive letter (like F:) to the path "\\computer2\sharedfolder". Then it just looks like the F: drive on computer1.
Share your App.Path to the domain. Then on the other system, point it's App.Path to your share.
If you want to dynamically select your path and/or file, then use the FileOpen dialog/control.
As for code examples, I haven't used real VB6 in almost 5 years, so I do not have any true examples or anyway to make one. The closest I can come is Excel VBA 6.5. Here is an example of a VBA function that I use in Excel to browse for and open an Access database:
Public Function OpenDB() As Boolean
'Open the Database and indicate if successful'
If IsOpen Then
OpenDB = True 'we are already open'
Exit Function
End If
If sFile = "" Then sFile = GetSetting("YourAppName", "History", "DBName")
With Application.FileDialog(msoFileDialogFilePicker)
'specify the file open dialog'
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Access Workbooks", "*.mdb"
.Filters.Add "All Files", "*.*"
.InitialFileName = sFile
.Title = "Open TIP Database"
.Show
If .SelectedItems.Count > 0 Then
sFile = .SelectedItems(1)
Else 'user canceled ...'
OpenDB = False
Exit Function
End If
End With
DB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFile
On Error Resume Next
DB.Open
If Err.Number <> 0 Then
MsgBox "Error(" & Err.Number & "): " & Err.Description, vbOKOnly + vbCritical, "Error in OpenDB"
OpenDB = False
Exit Function
End If
'Opened ok, so finsh-up and exit'
OpenDB = True
SaveSetting "YourAppName", "History", "DBName", sFile
End Function
You will have to replace the "Application.FileDialog" with a reference to a VB Forms FileDialog control/component, which you should drop onto your VB from from the toolbox (its actually a component-control, so it's not really visible).
You should expect that it will have some differences because these are GUI features and the VB Forms GUI is radically different from the Excel GUI. So the properties & settings might be different and you'll have to play around with them or look them up in VB Help.
Note: the GetSetting and SaveSetting stuff is just saving the last file name and path used in the registry, so that it can use it as the default location for the next time.
Related
ok so I was creating an HTML that opens without toolbars or anything just by itself but I can't make it work for other computers
this is what I got
set webbrowser = createobject("internetexplorer.application")
webbrowser.statusbar = false
webbrowser.menubar = false
webbrowser.toolbar = false
webbrowser.visible = true
webbrowser.navigate2 ("C:\Users\unknown\Desktop\Folder\myhtml.html")
You should handle that:
The user desktop folder location can be changed
The desktop a user sees is a virtual view of more than one folder in the filesystem. Directly searching for the folder inside the user desktop will leave out the desktop folder configured for all the users.
So, it is better to ask the OS to retrieve the required information
Option Explicit
' folder in desktop and file in folder
Const FOLDER_NAME = "Folder"
Const FILE_NAME = "myhtml.html"
Dim oFolder
Const ssfDESKTOP = &H00&
' Retrieve a reference to the virtual desktop view and try to retrieve a reference
' to the folder we are searching for
With WScript.CreateObject("Shell.Application").Namespace( ssfDESKTOP )
Set oFolder = .ParseName(FOLDER_NAME)
End With
' If we don't have a folder reference, leave with an error
If oFolder Is Nothing Then
WScript.Echo "ERROR - Folder not found in desktop"
WScript.Quit 1
End If
Dim strFolderPath, strFilePath
' Retrieve the file system path of the requested folder
strFolderPath = oFolder.Path
' Search the required file and leave with an error if it can not be found
With WScript.CreateObject("Scripting.FileSystemObject")
strFilePath = .BuildPath( strFolderPath, FILE_NAME )
If Not .FileExists( strFilePath ) Then
WScript.Echo "ERROR - File not found in desktop folder"
WScript.Quit 1
End If
End With
' We have a valid file reference, navigate to it
With WScript.CreateObject("InternetExplorer.Application")
.statusBar = False
.menubar = False
.toolbar = False
.visible = True
.navigate2 strFilePath
End With
You can find more information on shell scriptable objects here
Use the UserName property of the ActiveX-object "WScript.Network" to obtain the name of the current user on the other computers.
As in:
>> sUser = CreateObject("WScript.Network").UserName
>> WScript.Echo "Just for Demo:", sUser
>>
Just for Demo: eh
(That object is different from the WScript object provided by the C|WScript.exe host, so it's usable from other host. Not using the browser (.html), but the mshta.exe host (.hta) - as #omegastripes proposes - is sound advice.)
I am using the script listed below (I honestly stole this probably from this very site) for a browse button on a form. The task is simply to start up MS File Dialog box so that a file (in this case an image file) can be selected. Once you select the record and click ok it then pastes the file name and location into a field.
Viewing the table the file name and location is pasted just as it should be. The problem comes in with a report I built. I have an image set to display with the control source linked back to that file address field. It will not display the image though.
However, if I manually type the same address character for character or even “copy”, delete, and then “paste” the same exact entry into the field the image then displays just fine on the report.
I have checked to make sure there are no spaces or characters anywhere there shouldn’t be. I am at a loss here.
Any help would be greatly appreciated and I will gladly give you my first born. Ok maybe not the first I like him but you can have the second one, she’s hell.
Private Sub Command67_Click()
On Error GoTo SubError
'Add "Microsoft Office 14.0 Object Library" in references
Const msoFileDialogFilePicker As Long = 3
'Dim FD As Office.FileDialog
Dim FDialog As Object
Dim varfile As Variant
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
EmployeePicture = ""
' Set up the File Dialog
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
With FDialog
.Title = "Choose the spreadsheet you would like to import"
.AllowMultiSelect = False
.InitialFileName = "C:\Users\" 'Folder picker needs trailing slash
.Filters.Clear
.Filters.Add "All", "*.*"
If .Show = True Then
If .SelectedItems.Count = 0 Then
'User clicked open but didn't select a file
GoTo SubExit
End If
'An option for MultiSelect = False
'varFile = .SelectedItems(1)
'EmployeePicture = varFile
'Needed when MultiSelect = True
For Each varfile In .SelectedItems
EmployeePicture = EmployeePicture & varfile & vbCrLf
Next
Else
'user cancelled dialog without choosing!
'Do you need to react?
End If
End With
SubExit:
On Error Resume Next
Set FDialog = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & " = " & Err.Description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub
I am running MS Office 2013, and I'm trying to list files in an smb directory from Excel VBA code.
unix_path = "\\smb" & unix_path
ListBox3.Clear
Dim fil As file
On Error Resume Next
If Dir(unix_path, vbDirectory) <> "" Then
Set MyObject = New Scripting.FileSystemObject
Set mysource = MyObject.GetFolder(unix_path)
For Each myFile In mysource.Files
If InStr(myFile.Name, ".xlsx") > 0 Then
UserForm1.ListBox3.AddItem myFile.Name
End If
This takes about 15 seconds. The directory itself has only 5 files in it.
It is worth mentioning that accessing the directory directly from explorer is much faster (less than 1 second).
FSO has a lot of overhead from my experience and I have experienced some odd issues over our network with it. I do not frequently use it unless I am doing something more specific than this situation.
Please test the following code and see if it still hangs,
unix_path = "\\smb" & unix_path
ListBox3.Clear
Dim fil As file
On Error Resume Next
If Dir(unix_path, vbDirectory) <> "" Then
mySource = Dir(unix_path & "*.xlsx")
Do until mySource = ""
UserForm1.ListBox3.AddItem mySource
mySource = Dir()
loop
end if
Using VB6
Code.
CommonDialog1.DialogTitle = "Open File"
CommonDialog1.Filter = "*.*"
CommonDialog1.FilterIndex = 1
CommonDialog1.Flags = cdlOFNAllowMultiselect + cdlOFNExplorer
CommonDialog1.Flags = cdlOFNFileMustExist + cdlOFNHideReadOnly
CommonDialog1.CancelError = True
On Error Resume Next
CommonDialog1.ShowOpen
If Err Then
'MsgBox "Select Folder"
Exit Sub
End If
From the above code, i am selecting a file, But i don't want to select a file, I want to select only the folder. How to modify my code.
Need vb6 code Help?
It's been a while since I've had to do any visual basic work but I think instead of using the common dialog box for getting the name of a file to open you should use the SHBrowseForFolder function which is already part of the Windows API. Here's a link to a page that describes it's usage.
Update (2017): Provided link is broken but a backed-up version can be viewed on archive.org
To select a folder, you can use the Shell and Automation Component.
Private shlShell As Shell32.Shell
Private shlFolder As Shell32.Folder
Private Const BIF_RETURNONLYFSDIRS = &H1
Private Sub Command1_Click()
If shlShell Is Nothing Then
Set shlShell = New Shell32.Shell
End If
Set shlFolder = shlShell.BrowseForFolder(Me.hWnd, "Select a Directory", BIF_RETURNONLYFSDIRS)
If Not shlFolder Is Nothing Then
MsgBox shlFolder.Title
End If
End Sub
You will need to add a reference to shell32.dll to your project. Use the Project/References... menu and then browse for shell32.dll.
Or you can use the Windows API as Twotymz suggests.
This is an old thread, but maybe someone will be helped by this.
This code works in VB6 for me:
Private Sub ChooseDir_Click()
Dim sTempDir As String
On Error Resume Next
sTempDir = CurDir 'Remember the current active directory
CommonDialog1.DialogTitle = "Select a directory" 'titlebar
CommonDialog1.InitDir = App.Path 'start dir, might be "C:\" or so also
CommonDialog1.FileName = "Select a Directory" 'Something in filenamebox
CommonDialog1.Flags = cdlOFNNoValidate + cdlOFNHideReadOnly
CommonDialog1.Filter = "Directories|*.~#~" 'set files-filter to show dirs only
CommonDialog1.CancelError = True 'allow escape key/cancel
CommonDialog1.ShowSave 'show the dialog screen
If Err <> 32755 Then ' User didn't chose Cancel.
Me.SDir.Text = CurDir
End If
ChDir sTempDir 'restore path to what it was at entering
End Sub
I though that is more general VBA question anyway, opening select folder dialog in VBA for Office >=2k3.
I could not believe that it is so hard, as I need same functionality. Little googling made it.
Here is nice simple solution take a look
Function GetFolderName()
Dim lCount As Long
GetFolderName = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Show
For lCount = 1 To .SelectedItems.Count
GetFolderName = .SelectedItems(lCount)
Next lCount
End With
End Function
I'm trying to use Winsock to download some files and save them.
In my case, I have a MSHFlexGrid with 2 columns: one with URL and the other with the "path+filename" (where the file is going to be saved).
I'm iterating through all rows calling the next function:
Public Function DownloadSock(ArqURL As String, ArqDestino As String) As Boolean
'ArqURL is the file URL
'ArqDestino is where the downloaded file is going to be stored, in my hard disc
Dim arquivo() As Byte
Dim ficheiroID As Integer
ficheiroID = FreeFile
On Error GoTo Trata_erro
Open ArqDestino For Binary Access Write As #ficheiroID
Me.Winsock1.Connect ArqURL, 80
Me.Winsock1.GetData arquivo()
Put #ficheiroID, , arquivo()
Close #ficheiroID
DownloadSock = True
Exit Function
Trata_erro:
MDIForm1.Text1 = MDIForm1.Text1 & "Error! " & Err.Number & Err.Description & " - " & Err.Source & " - URL: " & ArqURL & " - Destino: " & ArqDestino & vbNewLine
DownloadSock = False
End Function
I'm getting this error
40006: Wrong protocol or connection
state for the requested transaction or
request
What am I doing wrong?
Have you checked out this Microsoft Support page? It indicates there's a bug in the Winsock control and the hotfix may be helpful.
Another thing to try is to make sure your winsock connection is open before trying to read/send data, and if it is closed, reopen a new connection:
if winsock.state=9 ' error state
winsock.close
while winsock.state<>0 ' closed state
doEvents
wend ' you need a while loop, because it doesn't close "immediately".
end if
' now you reopen it, or do whatever else you need
You might also consider changing your connection code to something like:
With Winsock1
If .State <> sckClosed Then .Close
.RemoteHost = ArqURL
.RemotePort = 80
.Connect
End With
One last thing. Check out this post on using the Winsock control.
I think you have overestimated the power of the Winsock control. You can't just use the Winsock's GetData method to reach out and grab a file. There has to be an active connection between your client application and some other application on the server side. After a connection is established, this server application will feed data to your application, the Winsock's DataArrival event will fire, and then you can use the GetData method to retrieve it. Your code should look more like this:
Public Sub DownloadSock(ArqURL As String)
Dim arquivo() As Byte
Dim ficheiroID As Integer
ficheiroID = FreeFile
Me.Winsock1.Connect ArqURL, 80
End Function
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim ArqDestino As String
Dim arquivo() As Byte
Dim ficheiroID As Integer
ficheiroID = FreeFile
Open ArqDestino For Binary Access Write As #ficheiroID
Me.Winsock1.GetData arquivo()
Put #ficheiroID, , arquivo()
Close #ficheiroID
End Sub
This is far from complete however (nor is it guaranteed to be syntactically correct, consider it pseudo code). After making the connection, you then have to implement some mechanism to tell the server to begin sending the file. If the file is large enough it will take many DataArrival events to get it all, so it will have to be held in an accumulator while the data comes across. There's more to this than you think.
I would take a look at some tutorials and/or sample code (look for a VB6 project that uses the Winsock control on CodeProject, like this one).