Question

That code is used to attach files, each file i attach(select) get one new position in filepath(). And in my form i have 8 textbox(invisible by default). What im trying to do is, when filepath(1) is filled(by the attach), textbox1 becomes visible, when filepath(2) is filled(by the attach) textbox2 becomes visible. . . . .

My code:

    Dim filepath() As String 

    Private Sub CommandButton4_Click() 

        Const msoFileDialogOpen = 1 
        Set fso = CreateObject("Scripting.FileSystemObject") 
        Set objWord = CreateObject("Word.Application") 
        Set WshShell = CreateObject("WScript.Shell") 
        strInitialPath = WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop\" 
        objWord.ChangeFileOpenDirectory (strInitialPath) 
        With objWord.FileDialog(msoFileDialogOpen) 
            .Title = "Select the file to process" 
            .AllowMultiSelect = True 
            .Filters.Clear 
            .Filters.Add "All Files", "*.*" 
            .Filters.Add "Excel Files", "*.xls;*.xlsx" 
            .Filters.Add "Text Files", "*.txt" 
            .Filters.Add "Various Files", "*.xls;*.doc;*.vbs" 
            If .Show = -1 Then 

                Dim filePath() As Variant
Dim myFile As Variant
Dim num As Integer: num = 1
'On Error Resume Next
'num = UBound(filepath)
'On Error GoTo 0


'### Redim this array as a base-1 array
ReDim Preserve filePath(num To .SelectedItems.Count)

'### I made some revisions here:
For Each file In .SelectedItems
    Set objFile = fso.GetFile(file)
    filePath(num) = file  'Store a string, rather than an object.
    Me.Controls("TextBox" & num).value = file
    num = num + 1
Next
            Else 

            End If 

        End With 

    End Sub 

Thanks,

Was it helpful?

Solution

You have undeclared variables in your code and a totally unnecessary use of On Error Resume Next where you attempt to get the Ubound(filePath) before you instantiate filePath as an array.

GET RID OF THESE LINES:

'        On Error Resume Next 
'        num = UBound(filepath) 
'        On Error Goto 0 ) 

You should declare your variables properly. Your user form must contain textbox controls named like TextBox1, TextBox2, ... TextBox8.

Dim filePath() as Variant
Dim myFile as Variant
Dim num As Integer: num = 1 

'### Redim this array as a base-1 array
Redim Preserve filepath(num to .SelectedItems.Count) 

'### I made some revisions here:
For Each file In .SelectedItems 
    Set objFile = fso.GetFile(file) 
    filepath(num) = file  'Store a string, rather than an object.   
    Me.Controls("TextBox" & num).Value = file
    num = num + 1 
Next 
TextBox14.Text = num & (" - Ficheiro(s) Adicionado(s)") 

Code is working and displays 6 different selections in an example file that I created:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top