Using Textbox as procedure(sub) input parameter - vba

I have some trouble with my code. I'll be glad if you can help me to where i am wrong.
This is my sheet's (name is SetSheet) code section; cmdSelProjectDir_Click() is my ActiveX command button which i try to select my working directory. SetSheet.txtSetWorkDir is my ActiveX textbox, selected directory path written into this. GetFolder(txtDir) is my procedure i call it from "Settings" module.
But i didn't built in proper way it gaves an error like that "Type Mismatch". But i don't know how is it possible to apply this type of strcture to code because i will be use this GetFolder subprocedure also on my other sheets.
'/SetSheet Page
Sub cmdSelProjectDir_Click()
Dim txtDir As TextBox
Set txtDir = SetSheet.txtSetWorkDir
Call Settings.GetFolder(txtDir)
End Sub
And here my procedure;
'/GetFolder procedure from Settings module.
Sub GetFolder(txtDir As TextBox)
Dim fdo As FileDialog
Dim sDir As String
Set fdo = Application.FileDialog(msoFileDialogFolderPicker)
With fdo
.Title = "Select a Directory"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sDir = .SelectedItems(1)
txtDir.Value = sDir
Debug.Print txtDir.Value; sDir
End With
NextCode:
' GetFolder = sDir
Set fdo = Nothing
End Sub

You have to use MSForms.TextBox instead of TextBox for an ActiveX text box:
Dim txtDir As MSForms.TextBox
and
Sub GetFolder(txtDir As MSForms.TextBox)

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.

Selecting a File with File Dialog From Function

I'm trying to use below code to selecting a file and write it's path and filename to textbox. I tried from a Worksheet with codename TESTAREA But i'm always get an error Type Mismatch.
I'm using below procedure to use function from sheet TEST_AREA(TESTAREA) Sheet Name (Code Name)
Private Sub CommandButton1_Click()
Call myFunctions.SelectFile(TESTAREA, "*.txt", TextBox1)
End Sub
This is function
Function SelectFile(ByVal strSheetName As Worksheet, strFilterExt As String, strTextBox As TextBox)
Dim fdo As Office.FileDialog
Set fdo = Application.FileDialog(msoFileDialogFilePicker)
With fdo
.InitialFileName = AUTOMBS.path
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "All Files", strFilterExt
If .Show = True Then
strSheetName.strTextBox.Value = .SelectedItems(1)
End If
End With
End Function
Could you please help me where i'm wrong ?
This worked for me. I added an ActiveX TextBox to Sheet1 and used your code. It gave me a Type Mismatch until I changed the function to take a MSForms.TextBox instead.
Sub Test()
Debug.Print GetName(Sheet1.TextBox1)
End Sub
Function GetName(tb As MSForms.TextBox)
GetName = tb.Value
End Function
So try this. I changed it to a Sub because you aren't returning anything to the Function!
Sub SelectFile(ByVal strSheetName As Worksheet, strFilterExt As String, strTextBox As MSForms.TextBox)
Dim fdo As Office.FileDialog
Set fdo = Application.FileDialog(msoFileDialogFilePicker)
With fdo
.InitialFileName = AUTOMBS.path
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "All Files", strFilterExt
If .Show = True Then
strTextBox.Value = .SelectedItems(1)
End If
End With
End Sub

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

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

Excel VBA ignores my IF statement to exit the sub

Excel ignores my programming statement that it should exit the sub if the item count is nothing
Given that it ignored the first IF statement, I tried to simply catch it with a second one, but it ignores that as well!
The code not only executes, but it just skips over all statements, and if I try to go through it line by line using F8, then it executes the full code.
I don't understand why it does this or what could cause it... Any help is appreciated.
Private Sub SelectFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
.Show
If .SelectedItems.Count = 0 Then
Exit Sub
Else
sPfad = .SelectedItems(1)
End If
End With
If sPfad = "" Then Exit Sub
End Sub
UPDATE:
After getting this response which worked well when I tried it stepping through the code automatically, I realized that when I ran the whole procedure, my problem persisted.
Today I finally learned what is happening... the sub does in fact, as programmed, stop and end. THAT particular sub. However, since I'm calling it from a different sub in a procedure, the code then goes back to the calling sub and continues.
What I needed was simply to change Exit Sub to End since I needed the whole procedure to stop!
Try this one:
Sub SelectFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
If Not .Show Then Exit Sub
sPfad = .SelectedItems(1)
End With
End Sub
when user press "Cancel" - .Show returns 0 (False). But if user press "OK" - current folder in FileDialog window is selected
A different approach:
Private Sub SelectFolder()
Dim strPath As Variant
Dim sPfad As Variant
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & " \"
.Title = "Select Folder"
End With
strPath = Application.FileDialog(msoFileDialogFolderPicker).Show
If strPath = False Then
Exit Sub
Else
sPfad = strPath
End If
End Sub

Multiple dialog boxes in VB

I'm having an issue that when I try to use multiple instances of file dialogs the information from the first is always overwritten by the selection in the second dialog.
What i need to do is:
Select a template file
Select a destination folder
Save the template file as a .docm file.
What happens is that the second time application.FileDialog is used all the information in fd is lost and is overwritten by the entries into fldr.
Can there only be one dialog object per macro?
Dim fd As FileDialog
Dim FileChosen As Integer
Dim FileName As String
Dim fldr As FileDialog
Dim fldrSelect As String
Dim i As Integer
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'use the standard title and filters, but change the
'initial folder
fd.InitialFileName = "H:\UpdatedSalesTemplates\"
fd.InitialView = msoFileDialogViewList
'allow multiple file selection
fd.AllowMultiSelect = True
FileChosen = fd.Show
If FileChosen = -1 Then
'Select the directory using a file dialog
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
fldr.InitialView = msoFileDialogViewList
fldr.Title = "Select Destination"
fldr.AllowMultiSelect = False
fldrSelected = fldr.Show
'
Microsoft says that there may be only one: "...Each host application can only create a single instance of the FileDialog object...".
In any case, this shouldn't represent a serious problem as far as you can store all the relevant information (selected path, initial directory, etc.) in (string) variables.
For such scenarios where you need a file/folder picker in one macro/procedure/userform, I use a custom made userform. See if you like it. Place commandbuttons and textboxes as shown below
Screenshot
Code
Note: Both the textboxes .Locked property was set to True in design time so that the user cannot modify the textboxes manually.
Option Explicit
Dim Ret
'~~> Browse File
Private Sub CommandButton1_Click()
Ret = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx")
If Ret <> False Then TextBox1.Text = Ret
End Sub
'~~> Browse Folder
Private Sub CommandButton2_Click()
Ret = BrowseForFolder("C:\")
If Ret <> False Then TextBox2.Text = Ret
End Sub
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
Dim ShellApp As Object
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
Set ShellApp = Nothing
Select Case Mid(BrowseForFolder, 2, 1)
Case Is = ":"
If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
Case Is = "\"
If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
Case Else
GoTo Invalid
End Select
Exit Function
Invalid:
'~~> If it was determined that the selection was invalid, set to False
BrowseForFolder = False
End Function