VBA:从数组中创建选定的字符串

问题描述 投票:0回答:1

编辑:提前感谢您的帮助。我想循环一个数组并创建一个字符串,直到不再满足条件。我认为我当前的代码创建了一个无限循环。

我在数组中有以下内容(子节以“ - ”开头)。 NB请忽略引号 - 破折号格式到子弹,所以不得不把它们放在那里停止。

“ - 第2分节”

“ - 第3款”

“第二节”

“ - 第4分节”

“第三节”

“ - 第5分节”

我想创建一个新的字符串,它只存储以“ - ”开头的字符串/数组插槽,直到排除下一个不以“ - ”开头的字符串。我想要的结果字符串是:

“ - 第1分节”

“ - 第2分节”

“ - 第3款”

(不包括“ - 第4分节”和“ - 第5分节”)

基本上我想要在同一“主”部分内的其余子部分。

以下是我对此的尝试:

Dim testArray() As Variant
Dim count1 As Integer
Dim CurrentSectionIndex as Integer

CurrentSectionIndex = ActivePresentation.Slides(i).sectionIndex



    count1 = ActivePresentation.SectionProperties.Count - CurrentSectionIndex


    'clear previous array (I am looping through slides)
    Erase testArray
    ' size the array

    ReDim testArray(1 To count1)


    'Fill the array


    For n = 1 To count1

        testArray(n) = ActivePresentation.SectionProperties.Name(CurrentSectionIndex + n)

        Next n


            Dim AllPostSections As String
            Dim PostSections As String


            For m = LBound(testArray) To UBound(testArray)

            Do While testArray(m) Like "-*"
            PostSections = testArray(m)

            Loop   

            AllPostSections = AllPostSections & PostSections & vbNewLine
            Next m

任何帮助将不胜感激!

arrays vba powerpoint do-while
1个回答
0
投票

关于为何使用Do While / Until循环的基本假设是正确的,但是您的实现是不正确的。对于您正在尝试实现的任务,您不需要使用Do While循环作为循环,您需要的是For M循环。然后在For循环中,您需要做的就是使用If语句测试来组合您想要的字符串。如果你想要你可以用Do while循环替换for for next循环,但实际上使用集合更容易实现你想要的东西。您可以使用与数组相同的方式索引集合中的项目,因此除非您查看变量定义,否则可以判断my_array(1)是使用数组还是集合。

下面的代码将收集所有标题(测试数组)的集合,并生成一个新集合,其中只有连接的子标题。

Option Explicit

Dim my_headings                         As Collection
Dim my_heading                          As Variant
Dim my_subheadings                      As Collection
Dim my_collector                        As String

my_collector = vbNullString
' fill the my_heading collection
Set my_subheadings = New Collection

For Each my_heading In my_headings

    If my_heading Like "-*" Then

        my_collector = my_collector & my_heading & vbCrLf

    Else

        If Len(my_collector) > 0 Then

            my_sub_headings.Add my_collector
            my_collector = vbNullString

        End If

    End If

Next

编辑:这是与上面相同的逻辑,但for for循环替换为do while循环。希望这将澄清你对While循环做什么的相当困惑的想法。

Dim my_headings                         As Collection
Dim my_subheadings                      As Collection
Dim my_collector                        As String
Dim my_index                            As Long
my_collector = vbNullString
' fill the my_heading collection
Set my_subheadings = New Collection

my_index = 1

Do While my_index <= my_headings.Count

    If my_headings(my_index) Like "-*" Then

        my_collector = my_collector & my_heading & vbCrLf

    Else

        If Len(my_collector) > 0 Then

            my_sub_headings.Add my_collector
            my_collector = vbNullString

        End If

    End If

    my_index=my_index+1

Loop
© www.soinside.com 2019 - 2024. All rights reserved.