strConv将括号视为第一个字母

时间:2015-06-28 17:20:14

标签: excel vba excel-vba

下面的代码中的strConv返回 (你好,世界) 而不是期望的 (你好,世界) 因为它将第一个括号视为单词“HELLO”的第一个字母。 任何人都可以建议如何克服这个问题吗?

 Dim MyString
    Dim MyCaseString
        MyString = "(HELLO WORLD)"
        MyCaseString = strConv(MyString, 3)
    MsgBox MyCaseString 

3 个答案:

答案 0 :(得分:1)

使用Mid()切掉前导“(” - 可以添加回来:

Sub test()
    Dim MyString
    Dim MyCaseString
    MyString = "(HELLO WORLD)"
    MyCaseString = "(" & StrConv(Mid(MyString, 2), 3)
    MsgBox MyCaseString
End Sub

答案 1 :(得分:1)

我个人使用正则表达式(您需要引用Microsoft VBScript Regular Expressions 5.5):

Dim regex As New RegExp
Dim matches As MatchCollection
Dim word As Match

Dim sample As String
sample = "(HELLO WORLD)"

With regex
    .Pattern = "\w+"
    .Global = True
    Set matches = .Execute(sample)
End With

For Each word In matches
    sample = Replace$(sample, word, StrConv(word, vbProperCase))
Next word

Debug.Print sample 

答案 2 :(得分:0)

如John Coleman,使用Replace函数可以做同样的事情。

  1. 方法1 - >这将替换左括号
  2. 方法2 - >这将替换左/右括号
  3. 方法1:

    Sub Test1()
    
        Dim MyString
        Dim MyCaseString
    
        MyString = "(HELLO WORLD)"
        MyCaseString = "(" & StrConv(Replace(MyString, "(", ""), 3)
    
        MsgBox MyCaseString
    End Sub
    

    方法2:

    Sub Test2()
    
        Dim MyString
        Dim MyCaseString
    
        MyString = "(HELLO WORLD)"
    
        mystr = Replace(Replace(MyString, "(", ""), ")", "")
        MyCaseString = "(" & StrConv(mystr, vbProperCase) & ")"
    
        MsgBox MyCaseString
    End Sub