【问题标题】:How to join characters in an array into a string?如何将数组中的字符连接成字符串?
【发布时间】:2020-04-02 17:41:11
【问题描述】:

我正在尝试将文本转换为 Spongebob 模拟样式文本,如下所示:

世界你好! = 你好,世界。

我将字符串拆分为数组并转换了字母,但我不能只将它们打印为数组。

如何将字符连接成字符串?

Private Sub CommandButton1_Click()
Dim Word As String
Dim i As Integer
Dim Letters() As String

Word = Sheet1.Range("A1").Value

Letters = Split(StrConv(Word, 64), Chr(0))
For i = 0 To Len(Word) - 1 Step 2
    Debug.Print StrConv(Letters(i), 1)
    Debug.Print StrConv(Letters(i + 1), 2)
Next i

End Sub

【问题讨论】:

  • 您是否尝试过使用Join
  • 或者使用临时字符串变量并将每个字符连接到循环中的临时字符串?
  • @BigBen 我在下一次我 Result = Join(lower, "") Debug.Print Result 将 lower 声明为数组后使用了这个,但它没有工作
  • @ScottCraner 我该怎么做?
  • temp = temp & StrConv(Letters(i), 1)

标签: arrays excel vba string


【解决方案1】:

对于您的代码,您需要做的就是创建一个新变量来保存新创建的字符串。

DIM allLetters As String

然后使用Join() 方法加入Letters()

allLetters = Join(Letters) 

这是关于加入的文档。

https://www.excelfunctions.net/vba-join-function.html

' Join together the strings "John", "Paul" and "Smith".
Dim fullName As String
Dim names( 0 to 2 ) As String
names(0) = "John"
names(1) = "Paul"
names(2) = "Smith"
fullName = Join( names )
' The variable fullName is now set to "John Paul Smith"

参考

VBA 连接函数。 (未注明日期)。取自https://www.excelfunctions.net/vba-join-function.html

【讨论】:

  • 感谢您的帮助,我不知道如何正确使用join方法。 @BigBen 告诉我如何以及在何处将其添加到脚本中。现在可以了!
【解决方案2】:

使用Join 连接字符数组。可以直接修改Letters的内容,得到大小写交替,如下所示:

Private Sub CommandButton1_Click()
    Dim Word As String
    Word = Sheet1.Range("A1").Value

    Dim Letters() As String
    Letters = Split(StrConv(Word, 64), Chr(0))

    Dim i As Long
    For i = LBound(Letters) To UBound(Letters)
        If i Mod 2 = 0 Then
            Letters(i) = StrConv(Letters(i), 2) '<~ or `LCase$`
        Else
            Letters(i) = StrConv(Letters(i), 1) '<~ or `UCase$`
        End If
    Next

    Debug.Print Join(Letters, "")
End Sub

【讨论】:

  • 这比我想要的想法要好得多。有用!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2012-11-28
  • 2023-04-02
  • 2014-11-04
  • 1970-01-01
  • 2015-05-02
相关资源
最近更新 更多