在文本框上加载数组值

时间:2014-05-07 13:47:27

标签: vba outlook-vba

该代码用于附加文件,我附加(select)的每个文件在filepath()中获得一个新位置。在我的形式我有8个文本框(默认情况下不可见)。我试图做的是,当文件路径(1)被填充(通过附加)时,textbox1变得可见,当文件路径(2)被填充时(通过附加),textbox2变得可见。 。 。 。

我的代码:

    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 

谢谢,

1 个答案:

答案 0 :(得分:0)

您的代码中有未声明的变量,并且在您将On Error Resume Next实例化为数组之前尝试获取Ubound(filePath)时完全不必要地使用filePath

获取这些线路:

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

您应该正确声明变量。您的用户表单必须包含名为TextBox1TextBox2,... 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)") 

代码正在运行,并在我创建的示例文件中显示6种不同的选择:

enter image description here