Создание и отображение Msgbox и вывод содержимого массива и длины слов на лист - PullRequest
0 голосов
/ 14 февраля 2019

Я пытаюсь создать Msgbox, который отображает все слова в столбце на листе.Затем создайте еще одно окно сообщения со счетчиком количества слов вместе со словами длиной более 5 символов.Я не совсем уверен, как создать Msgbox с указанными ниже переменными, поэтому я был бы признателен за некоторую помощь!

До сих пор я написал подпрограмму, которая импортирует одну строку текста из текстового файла, используя GetOpenFilename.Затем я использовал split для разбора файла с помощью разделителя.

Содержимое текстового файла выглядит следующим образом:

Загсы, беркуты, ястребы, павлины, борзые, золотые гриффены, доны, мушкетеры

Ниже приведен код Iдо сих пор:

Sub ImportTextFile()

Dim fileName As Variant     ' array will hold the file name or names to import

Dim i As Integer            ' counter for loops
Dim nLargeWords As Integer  ' counter for words longer than 5 characters

Dim dataLine As String      ' string to hold a single line of text from file
Dim lineCount As Integer

Dim arrWords() As String    ' array that will hold the contents of the text file
Dim msg As String           ' string for building the first message box

Const delim = ","           ' Added a constant for the delimiter in Split function

With Range("Output_lbl")
         Range(.Offset(1, 1), .Offset(100, 2)).ClearContents
End With

'============Navigate to file location and get filename of text file


fileName = Application.GetOpenFilename(, , "Select a text file", , False)       ' Used GetOpenFilename method to navigate to the file and obtain the file name.


'============Import file into temp string variable then parse into an array


Open fileName For Input As #1       ' To open the text file.
    i = 0
    With Range("Output_lbl")
        Do Until EOF(1)

            Line Input #1, dataLine             ' Setting the first line of the text file to a string variable.
            arrWords() = Split(dataLine, delim)         ' Using Split to parse the file. The delimiter was determined to be "," which was declared a constant above.
            For i = LBound(arrWords()) To UBound(arrWords())        ' Parse into an array.
                .Offset(i, 0) = Trim(arrWords(i))
            Next i
            i = i + 1
        Loop
    End With

Close #1                            ' To close the text file.


'============Create and display the message boxes and output array contents and word lengths to the output sheet.


End Sub

Одно окно сообщения должно быть отформатировано так:

Слова в файле.

Zags
Golden Eagles
Hawks
Peacocks
Greyhounds
Golden Griffins
Dons
Musketeers

Другое окно сообщения должно быть отформатировано какэто:

Microsoft Excel

Total Words:    8
Large Words:    5

1 Ответ

0 голосов
/ 14 февраля 2019

Пример кода без использования массива.Вам просто нужно изменить цикл, чтобы посмотреть переменный индекс в массиве, а не переменную строку в столбце цикла.Тогда используемая ниже логика должна быть легко распространена на вашу проблему.


Option Explicit

Sub Example()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim LR As Long, i As Long
Dim MyString As String, MyCounter As Long, Arr

LR = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

For i = 1 To LR
    MyString = MyString & ws.Range("A" & i) & ", "

    If Len(ws.Range("A" & i)) > 5 Then
        MyCounter = MyCounter + 1
    End If
Next i

MyString = Left(MyString, Len(MyString) - 2) 'Remove last ", "
Arr = Split(MyString, ", ")

MsgBox "Total Words: " & UBound(Arr) + 1 & vbNewLine & "Large Words: " & MyCounter


End Sub

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...