Caixa de diálogo Abrir/Salvar como

A muito tempo utilizei este módulo em um projeto, ele utiliza a comdlg32.dll para abrir a caixa de diálogo de procura e seleção de arquivos, com a principal vantagem de não precisar referenciar a comondlg em seu projeto.

Índice
Módulo
Form
Passo-a-passo

Topo 

Módulo -

Vamos utilizar um módulo, um form, uma caixa de texto e um botão.

1° passo, crie um novo módulo em seu arquivo com o seguinte conteúdo:

Option Compare Database
Option Explicit

'This code was originally written by Ken Getz.
'It is not to be altered or distributed,
'except as part of an application.
'You are free to use it in any application,
'provided the copyright notice is left unchanged.
'
' Code courtesy of:
' Microsoft Access 95 How-To
' Ken Getz and Paul Litwin
' Waite Group Press, 1996

Type tagOPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
strFilter As String
strCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
strFile As String
nMaxFile As Long
strFileTitle As String
nMaxFileTitle As Long
strInitialDir As String
strTitle As String
Flags As Long
nFileOffset As Integer
nFileExtension As Integer
strDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type

Declare Function aht_apiGetOpenFileName Lib "comdlg32.dll" _
Alias "GetOpenFileNameA" (OFN As tagOPENFILENAME) As Boolean

Declare Function aht_apiGetSaveFileName Lib "comdlg32.dll" _
Alias "GetSaveFileNameA" (OFN As tagOPENFILENAME) As Boolean

Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long

Global Const ahtOFN_READONLY = &H1
Global Const ahtOFN_OVERWRITEPROMPT = &H2
Global Const ahtOFN_HIDEREADONLY = &H4
Global Const ahtOFN_NOCHANGEDIR = &H8
Global Const ahtOFN_SHOWHELP = &H10
' You won't use these.
'Global Const ahtOFN_ENABLEHOOK = &H20
'Global Const ahtOFN_ENABLETEMPLATE = &H40
'Global Const ahtOFN_ENABLETEMPLATEHANDLE = &H80
Global Const ahtOFN_NOVALIDATE = &H100
Global Const ahtOFN_ALLOWMULTISELECT = &H200
Global Const ahtOFN_EXTENSIONDIFFERENT = &H400
Global Const ahtOFN_PATHMUSTEXIST = &H800
Global Const ahtOFN_FILEMUSTEXIST = &H1000
Global Const ahtOFN_CREATEPROMPT = &H2000
Global Const ahtOFN_SHAREAWARE = &H4000
Global Const ahtOFN_NOREADONLYRETURN = &H8000
Global Const ahtOFN_NOTESTFILECREATE = &H10000
Global Const ahtOFN_NONETWORKBUTTON = &H20000
Global Const ahtOFN_NOLONGNAMES = &H40000
' New for Windows 95
Global Const ahtOFN_EXPLORER = &H80000
Global Const ahtOFN_NODEREFERENCELINKS = &H100000
Global Const ahtOFN_LONGNAMES = &H200000

Function GetOpenFile(Optional varDirectory As Variant, _
Optional varTitleForDialog As Variant, _
Optional strDescription As String, Optional varItem, Optional varHwnd As Long) As Variant
'Incluídas as variáveis strDescription, varItem e varHwnd por JR.
' Here's an example that gets an Access database name.
Dim lngFlags As Long, strFilter As String
Dim varFileName As Variant
' Especifica que o arquivo escolhido já deve existir,
' não muda diretórios ao terminar. Também não mostra
' a caixa read-only.
lngFlags = ahtOFN_FILEMUSTEXIST Or _
ahtOFN_HIDEREADONLY Or ahtOFN_NOCHANGEDIR
If IsMissing(varDirectory) Then
varDirectory = ""
End If
If IsMissing(varTitleForDialog) Then
varTitleForDialog = ""
End If

' Define the filter string and allocate space in the "c"
' string Duplicate this line with changes as necessary for
' more file templates.
strFilter = ahtAddFilterItem(strFilter, strDescription, varItem)
' Now actually call to get the file name.
varFileName = ahtCommonFileOpenSave( _
OpenFile:=True, _
InitialDir:=varDirectory, _
Filter:=strFilter, _
Flags:=lngFlags, _
DialogTitle:=varTitleForDialog, _
hwnd:=varHwnd)

If Not IsNull(varFileName) Then
varFileName = TrimNull(varFileName)
End If
GetOpenFile = varFileName
End Function

Function ahtCommonFileOpenSave( _
Optional ByRef Flags As Variant, _
Optional ByVal InitialDir As Variant, _
Optional ByVal Filter As Variant, _
Optional ByVal FilterIndex As Variant, _
Optional ByVal DefaultExt As Variant, _
Optional ByVal FileName As Variant, _
Optional ByVal DialogTitle As Variant, _
Optional ByVal hwnd As Variant, _
Optional ByVal OpenFile As Variant) As Variant

' This is the entry point you'll use to call the common
' file open/save dialog. The parameters are listed
' below, and all are optional.
'
' In:
' Flags: one or more of the ahtOFN_* constants, OR'd together.
' InitialDir: the directory in which to first look
' Filter: a set of file filters, set up by calling
' AddFilterItem. See examples.
' FilterIndex: 1-based integer indicating which filter
' set to use, by default (1 if unspecified)
' DefaultExt: Extension to use if the user doesn't enter one.
' Only useful on file saves.
' FileName: Default value for the file name text box.
' DialogTitle: Title for the dialog.
' hWnd: parent window handle
' OpenFile: Boolean(True=Open File/False=Save As)
' Out:
' Return Value: Either Null or the selected filename
Dim OFN As tagOPENFILENAME
Dim strFileName As String
Dim strFileTitle As String
Dim fResult As Boolean
' Give the dialog a caption title.
If IsMissing(InitialDir) Then InitialDir = CurDir
If IsMissing(Filter) Then Filter = ""
If IsMissing(FilterIndex) Then FilterIndex = 1
If IsMissing(Flags) Then Flags = 0&
If IsMissing(DefaultExt) Then DefaultExt = ""
If IsMissing(FileName) Then FileName = ""
If IsMissing(DialogTitle) Then DialogTitle = ""
If IsMissing(hwnd) Then hwnd = Application.hWndAccessApp
If IsMissing(OpenFile) Then OpenFile = True
' Allocate string space for the returned strings.
strFileName = Left(FileName & String(256, 0), 256)
strFileTitle = String(256, 0)
' Set up the data structure before you call the function
With OFN
.lStructSize = Len(OFN)
.hwndOwner = hwnd
.strFilter = Filter
.nFilterIndex = FilterIndex
.strFile = strFileName
.nMaxFile = Len(strFileName)
.strFileTitle = strFileTitle
.nMaxFileTitle = Len(strFileTitle)
.strTitle = DialogTitle
.Flags = Flags
.strDefExt = DefaultExt
.strInitialDir = InitialDir
' Didn't think most people would want to deal with
' these options.
.hInstance = 0
.strCustomFilter = ""
.nMaxCustFilter = 0
.lpfnHook = 0
'New for NT 4.0
.strCustomFilter = String(255, 0)
.nMaxCustFilter = 255
End With

' This will pass the desired data structure to the
' Windows API, which will in turn it uses to display
' the Open/Save As Dialog.
If OpenFile Then
fResult = aht_apiGetOpenFileName(OFN)
Else
fResult = aht_apiGetSaveFileName(OFN)
End If

' The function call filled in the strFileTitle member
' of the structure. You'll have to write special code
' to retrieve that if you're interested.
If fResult Then
' You might care to check the Flags member of the
' structure to get information about the chosen file.
' In this example, if you bothered to pass in a
' value for Flags, we'll fill it in with the outgoing
' Flags value.
If Not IsMissing(Flags) Then Flags = OFN.Flags
ahtCommonFileOpenSave = TrimNull(OFN.strFile)
Else
ahtCommonFileOpenSave = "" 'alterado por JR.
End If
End Function

Function ahtAddFilterItem(strFilter As String, _
strDescription As String, Optional varItem As Variant) As String
' Tack a new chunk onto the file filter.
' That is, take the old value, stick onto it the description,
' (like "Databases"), a null character, the skeleton
' (like "*.mdb;*.mda") and a final null character.

If IsMissing(varItem) Then varItem = "*.*"
ahtAddFilterItem = strFilter & _
strDescription & vbNullChar & _
varItem & vbNullChar
End Function

Private Function TrimNull(ByVal strItem As String) As String
Dim intPos As Integer
intPos = InStr(strItem, vbNullChar)
If intPos > 0 Then
TrimNull = Left(strItem, intPos - 1)
Else
TrimNull = strItem
End If
End Function

Nesse momento não iremos discutir o funcionamento deste módulo.

Topo 

Form -

Crie um novo formulário com uma caixa de texto (nome=texto0) e um botão (nome=Comando2) e abra o código deste form
copie as seguinte funções e atributos:

Option Compare Database
Dim vardir As String


Private Sub Comando2_Click()
   Dim retorno
  'Passa o path do arquivo selecionado para a textbox Texto0.
   retorno = GetOpenFile(vardir, "Selecione um arquivo", _
  "All Files (*.*)", "*.*", Me.hwnd)
If retorno <> "" Or Not IsNull(retorno) Then
  Texto0 = retorno
  vardir = Updt_curdir(Texto0) 'atualiza com a pasta selecionada.
End If
End Sub

Private Sub Form_Load()
  vardir = Application.CurrentProject.path
End Sub

Function Updt_curdir(path As String) As String
  Dim arq As String
If IsNull(path) Or path = "" Then
  Exit Function
End If

  arq = Dir(path)
  Updt_curdir = Left(path, Len(path) - Len(arq))
End Function

Pronto!! agora ao clicar no botão, o código irá chamar a caixa de diálogo e armazenar o resultado na textbox e você pode continuar seu código.

Topo 

Passo-a-passo

' Dim vardir As String' = Declara a variável 'vardir' como variável privada, ou seja, pode ser utilizada em qualquer lugar do form aberto

Private Sub Comando2_Click() = inicia uma ação para o botão 'Comando2' na intervenção On_click
Dim retorno = declara localmente a variável 'retorno', ou seja, pode ser utilizada apenas dentro desta Sub
retorno = GetOpenFile(vardir, "Selecione um arquivo", _
"All Files (*.*)", "*.*", Me.hwnd) = chama a função GetOpenFile que gravamos no módulo, ela requisita as seguintes variáveis abaixo, e atribui o resultado a variável 'retorno' para que possamos utilizá-la

  1. varDirectory = valor para o caminho inicial onde a caixa de diálogo irá procurar no nosso caso, incluímos a vardir que falaremos mais adiante
  2. varTitleForDialog = Título da caixa de diálogo
  3. strDescription = Descrição do tipo de arquivo poderá ser localizado
  4. varItem = tipo de arquivo que poderá ser localizado, em nosso caso utilizamos "*.*" mas você pode incluir filtros como "*.JPG" ou "*.MDB;*.MDE", mas lembre-se de separar os tipo com uma comma " ; "
  5. varHwnd = objeto Hwnd da janela atual, em poucas palavras como a commondlg é uma função interna do windows e pode ser chamada em qualquer aplicativo ela precisa saber de onde está sendo chamada e a varHwnd linca a caixa de diálogo ao seu form.

If retorno <> "" Or Not IsNull(retorno) Then = verifica se foi selecionado algum arquivo foi selecionado
Texto0 = retorno = caso tenha sido selecionado aplica o valor da variável 'retorno' a nossa caixa de texto
vardir = Updt_curdir(Texto0) = chama a função 'Updt_curdir' que falaremos a seguir
End If = fecha a condicional
End Sub = fecha a ação do botão

Private Sub Form_Load() = inicia uma ação na intervenção On_Load do form
vardir = Application.CurrentProject.path = aplica um valor para a variável 'vardir' que declaramos no início do código. Application.CurrentProject.path = basicamente recupera a pasta onde o aplicativo está instalado.
End Sub

Function Updt_curdir(path As String) As String = função privada (válida somente no form atual) que irá atualizar o diretório atual processando a variável 'path'
Dim arq As String = declara localmente a variável 'arq'
If IsNull(path) Or path = "" Then = verifica se a variável 'path' está vazia
Exit Function = caso esteja sairá da função sem atualizar o diretório
End if

arq = Dir(path) = a função 'Dir' retorna o nome do arquivo ou diretório e então atribui o valor a variável 'arq'
Updt_curdir = Left(path, Len(path) - Len(arq)) = vamos por partes:

  1. Len(string) = retorna a quantidade de caracteres da string
  2. Left(string, length) = retorna a quantidade (length) de caracteres da string da esquerda da direita, vejamos um exemplo Left("spyderit.com.br",8)="spyderit"
  3. ou seja: Left(path 'string que contém o arquivo selecionado', Len(path 'quantidade de caracteres de path) - Len(arq 'quantidade de caracteres do arquivo)) irá retornar o caminho sem o nome, se tivermos em path="c:/spyderit.mdb" teremos como resultado "c:/"

End Function = encerra a função

Agora sim.

Abraço,
Flavio Ribeiro
www.spyderit.com.br