选择0个文件,但VBA Excel说我选择了1个文件

时间:2018-05-28 12:02:50

标签: excel vba excel-vba

我试图运行这个脚本,我想要一个消息框来说明我选择的打开文件的数量。但是,当我运行脚本iin VBA并单击文件选择器中的取消按钮而没有选择任何文件时,消息框的输出指出"您已选择1个文件"尽管我没有选择。有人可以帮帮我吗?

Public OpenFiles As Variant
Public FileNumber As Integer
Public TextFile As Workbook
Public FileNumberString As String

Public Sub OpenFile()

    OpenFiles = Application.GetOpenFilename(Title:="Select File(s) to Import", MultiSelect:=True)
    FileNumber = Application.Count(OpenFiles)
    FileNumberString = FileNumber
    MsgBox ("You have selected " + FileNumberString + " Files")
End Sub

我还编写了另一个属性,它只在FileNumber!= 0时运行。因此,这对我来说是一个问题:

Public Sub ImportTextFiles()

    Dim i As Integer
    Application.ScreenUpdating = False

    If FileNumber = 0 Then
        MsgBox ("You did not select a file. Please select at least one file")

    Else:
        For i = 1 To FileNumber
            Set TextFile = Workbooks.Open(OpenFiles(i))
            TextFile.Sheets(1).Range("A1").CurrentRegion.Copy
            Workbooks(1).Activate
            Workbooks(1).Worksheets.Add
            ActiveSheet.Paste
            ActiveSheet.Name = TextFile.Name
            Application.CutCopyMode = False

            TextFile.Close

        Next i

    End If

    Application.ScreenUpdating = False
End Sub

Public OpenFiles As Variant
Public FileNumber As Integer
Public TextFile As Workbook
Public FileNumberString As String

Public Function IsArrayAllocated(Arr As Variant) As Boolean
On Error Resume Next
IsArrayAllocated = IsArray(Arr) And _
                    Not IsError(LBound(Arr, 1)) And _
                    LBound(Arr, 1) <= UBound(Arr, 1)
End Function
Public Sub OpenFile()
    OpenFiles = Application.GetOpenFilename(FileFilter:="Text Files, *.txt", Title:="Select File(s) to Import", MultiSelect:=True)
    FileNumber = Application.CountA(OpenFiles)
    FileNumberString = CStr(FileNumber)
    MsgBox (IsArrayAllocated(OpenFiles))
    If IsArrayAllocated(OpenFiles) = False Then
        MsgBox ("You have selected 0 Files")
    Else:
        MsgBox ("You have selected " + FileNumberString + " Files")
    End If
End Sub

0 个答案:

没有答案