gpt4 book ai didi

arrays - MsgBox 中的打印数组删除尾随逗号

转载 作者:行者123 更新时间:2023-12-04 21:56:37 24 4
gpt4 key购买 nike

我有一个显示在 msgBox 中的数组通过 Join()功能。如果我使用 Join,我想知道如何删除出现的尾随逗号在 resultsFinal大批。

Function test2(Var As Range)
Dim result As Integer
Dim resultsFinal() As String
ReDim resultsFinal(0)
Dim i As Integer

i = 0

result = 0

Dim cell As Range
For Each cell In Var.Cells
If cell.Value = 25 Or cell.Value = 45 Then
result = result + 1
ReDim Preserve resultsFinal(result)
Dim temp As String

resultsFinal(i) = cell.Row
i = i + 1
test2 = cell.Value
End If
Next cell

Dim resultsFinal1() As String 'here is my try
resultsFinal1 = resultsFinal
ReDim Preserve resultsFinal1(result - 1) 'the length is smaller!
MsgBox result & " and " & vbNewLine & "array: " & Join(resultsFinal1, ", ") 'still displayes the full array, including the last character (but fortunately somehow doesn't display comma)

End Function

我还尝试创建一个 resultsFinal1初始数组减去最后一个元素的数组。它可以工作,但不如预期 - 不知何故,尽管 resultsFinal1 的长度小于 resultsFinal ,它仍然存储最后一个元素,逗号消失。为什么?

最佳答案

首先,您的数组总是大 1,因为数组索引从 0 开始。所以实际上 Redim resultsFinal(0) 创建了一个包含 1 个元素的数组。

所以通过从

result = result + 1
ReDim Preserve resultsFinal(result)


ReDim Preserve resultsFinal(result)
result = result + 1

你的数组大小变得正确。

第二部分,关键字 Join添加字符串 之间数组项,所以当你的数组变大 1 时,它添加了 ,在数组中最后一个正确的元素和一个空字符串之间,这实际上是数组中的最后一项。

关于arrays - MsgBox 中的打印数组删除尾随逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43287766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com