VBA Excel Choose File - When cancel is clicked it clears the textbox - vba

Basically I have a spreadsheet with a form on it. On that form there is a textbox that contains a file path which could be pre-populated from a cell on the sheet. But the user can choose to browse for another file. When they are browsing they have an option of "Open" or "Cancel". The open button works fine and populates the textbox, but if they choose cancel it clears the textbox if it is already populated. How can I stop the textbox being cleared?
I have narrowed it down to this block of code where it is happening:
Function GetFileName()
Set MyFile = Application.FileDialog(msoFileDialogOpen)
With MyFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Function
End If
GetFileName = .SelectedItems(1)
End With
End Function

This done the trick. Making sure the file name has a value before populating the textbox
Private Sub btnBrowse_Click()
Dim sFileName As String
sFileName = GetFileName()
If Len(sFileName) > 0 Then
TextBox1.Value = sFileName
End If
End Sub
Function GetFileName()
Set MyFile = Application.FileDialog(msoFileDialogOpen)
With MyFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Function
End If
GetFileName = .SelectedItems(1)
End With
End Function

Related

Importing doc variables from a Word document into another

I have a Word document with a userform that allows users to complete a series of questions (filing out textboxes) that populates a Word document. The userform utilizes doc variables to mark where in the document I want answers to be populated. The code looks like:
Dim TextBox13 As Range
ActiveDocument.Variables("dvmdy").Value = Me.TextBox13.Value
Me.TextBox13.Value = Me.TextBox13.Text
With ActiveDocument
.Fields.Update
End With
I also have a command button that works to open another document but am trying to make it so it reads the docvariables in the second document and writes them to the first. The code below is for the file selector setup I put together:
Private Sub CommandButton1_Click()
Dim fDialog As FileDialog
Dim strFile1 As String
Dim strFile2 As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Filters.Clear
.Filters.Add "Word Documents", "*.docm*"
.InitialFileName = "C:\"
.Title = "Select the First Document"
If .Show = -1 Then
strFile1 = .SelectedItems(1)
strFile1 = .SelectedItems(1)
MsgBox (strFile1)
Label8v = strFile1
Else
Exit Sub
End If
End With
With fDialog
.Filters.Clear
.Filters.Add "Word Documents", "*.docm*"
.InitialFileName = "C:\"
.Title = "Select the Second Document"
If .Show = -1 Then
strFile2 = .SelectedItems(1)
strFile2 = .SelectedItems(1)
MsgBox (strFile2)
Label9v = strFile2
Else
Exit Sub
End If
End With
Set Doc1 = Documents.Open(strFile1)
Set Doc2 = Documents.Open(strFile2)
End Sub
Basically I want to make it so it allows users to open previously filled out Word documents with the same doc variables so that the previously filled out answers could be used to populate the new document/userform.

Select file in dialogue box, place the path in text box, and another button for importing as a table

VBA to open a dialogue box by clicking buttons, select files individually, place the path in more than one text boxes, click another button to import the files
I have been searching on the web but all the codes have both selecting and importing in one program
'Module
Public Sub ImportDocument()
On Error GoTo ErrProc
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Some Title"
With .Filters
.Clear
.Add "TXT documents", "*.txt", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False
If .Show = 0 Then GoTo Leave
End With
Dim selectedItem As Variant
For Each selectedItem In fd.SelectedItems
DoCmd.TransferText acImportDelim, "team_Specs", "team", selectedItem, True, ""
'DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
Next
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Sub
ErrProc:
MsgBox err.Description, vbCritical
Resume Leave
End Sub
'Form
Private Sub Command2_Click()
Dim status_ As TaskImportEnum
status_ = ImportDocument
Select Case status_
Case TaskImportEnum.Success:
MsgBox "Success!"
Case TaskImportEnum.Failure:
MsgBox "Failure..."
Case Else:
MsgBox "Aborted..."
End Select
End Sub
You need to break down the import sub into multiple tasks.
The Select file Function returns only the file path of the selected document and the path is then inserted into the relevant TextBox.
The import button then validates the TextBox has a value and yes, it imports it.
1. Select file.
Private Sub ButtonSelect_Click()
Dim file_ As String
file_ = SelectDocument()
'Selection was made?
If file_ <> vbNullString Then TextBoxFilePath.Value = file_
End Sub
The Function to select a file.
Public Function SelectDocument() As String
On Error GoTo Trap
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Some Title"
With .Filters
.Clear
.Add "TXT documents", "*.txt", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False
End With
'if a selection was made, return the file path
If fd.Show = -1 Then SelectDocument = fd.SelectedItems(1)
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
2. Import if a selection has been made.
Private Sub ButtonImport_Click()
With TextBoxFilePath
If Not IsNull(.Value) Then
DoCmd.TransferText acImportDelim, "team_Specs", "team", .Value, True, ""
End If
End With
End Sub
You need to change the names of the Buttons and TextBoxes.

VBA Access - Application.FileDialog

Quick question, I have a simple bit of code which allows the user to click on a textbox and find the location of the required file. However, can I get this so that when the "Browser" popup appears, is so that it shows a specific file path ie; T:\Production
Private Sub SideProfile_Click()
Dim vrtSelectedItem As Variant
With Application.FileDialog(3)
.AllowMultiSelect = False
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
SideProfile = "#" & vrtSelectedItem & "#"
Next vrtSelectedItem
Else
End If
End With
End Sub
Add
.InitialFileName = CurrentProject.Path 'Or any path
to the With Application.FileDialog(3) block.

Excel File not Visible but Word file is

Form Workbook1 I'm launching the Opening_File Userform using the following code to keep the application hide and the form visible:
Sub ShowingForm()
Opening_File.Show (vbModeless)
Application.Visible = False
ThisWorkbook.Windows(1).Visible = False
End Sub
and I use the following code to open Excel and Word Files from the form:
Sub OpeningExcelFile()
Dim Finfo As String
Dim FilterIndex As Integer
Dim Title As String
Dim Filename As Variant
Dim wb As Workbook
Dim objWdApp As Object
Dim objWdDoc As Object
'Setup the list of file filters
Finfo = "Excel Files (*.xlsx),*xlsx," & _
"Macro-Enable Worksheet (*.xlsm),*xlsm," & _
"Word Files (*.docx),*.docx," & _
"All Files (*.*),*.*"
MultiSelect = True
'Display *.* by default
FilterIndex = 4
'Set the dialog box caption
Title = "Select a File to Open"
'Get the Filename
Filename = Application.GetOpenFilename(Finfo, _
FilterIndex, Title)
'Handle return info from dialog box
If Filename = False Then
MsgBox "No file was selected."
Exit Sub
Else
MsgBox "You selected " & Filename
End If
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
Set objWdApp = CreateObject("Word.Application")
objWdApp.Visible = True
Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If
End Sub
Opening Word files is not a problem but whenever I open Excel Files since Application.Visible = False, I have to Hide the form with :
Private Sub CommandButton2_Click()
Opening_File.Hide
Application.Visible = True
ThisWorkbook.Windows(1).Visible = True
End Sub
So I'm able to see the excel file opened. Is there anyway to keep the form visible with the workbook where I'm launching the form not visible but every workbook I open from the form visible? Thank you
I realize the best way to go in this kind of situations is to leave the ThisWorkbook.Windows(1).Visible = False witch would leave the application visible and also will allow me to see each workbook file opened from the form.
Sub ShowingForm()
Opening_File.Show (vbModeless)
Application.Visible = True
ThisWorkbook.Windows(1).Visible = False
End Sub

Excel User forms in vba

I'm developing VBA code using Forms. I have a certain button option to let the user select the workbook using FileDialog. The workbook file may contain 4 or 5 sheets itself. I have combobox with empty.
I need to have the sheetnames of the user selected workbook listed in the combobox automaticaly without opening the workbook.
I tried with the following code, but got the names of already opened workbooks.
Private Sub CommandButton2_Click()
Set myfile = Application.FileDialog(msoFileDialogOpen)
With myfile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
With Fileselected
For i = 1 To Sheets.Count
ComboBox2.AddItem Sheets(i).Name
Next i
End With
At the moment Sheets refers to the current workbook as you do nothing with Fileselected.
You must open the selected file, otherwise how can you examine its contents?
Set myfile = Application.FileDialog(msoFileDialogOpen)
With myfile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
Dim doc As Workbook
Set doc = Application.Workbooks.Open(Fileselected)
With doc
For i = 1 To .Sheets.Count
ComboBox2.AddItem .Sheets(i).Name
Next i
.Close
End With