【问题标题】:Inserting into an Excel VBA string插入 Excel VBA 字符串
【发布时间】:2021-05-21 18:09:41
【问题描述】:

在 JAVA 或 C++ 中,我们可以按照myString.insert(position, word) 的方式做一些事情。有没有办法在 Excel VBA 的字符串中做同样的事情?在我的工作表中,我有一个如下所示的字符串:01 / 01 / 995,我想在年份中插入 1,所以将其设为 01 / 01 / 1995

Dim test_date As String
test_date = "01 / 25 / 995"
test_date = Mid(test_date, 1, 10) & "1" & Mid(test_date, 11, 4)

还有其他更简单/更优雅的方法吗?

【问题讨论】:

  • 使用Mid$而不是Mid,前者是字符串函数,后者是变体函数。字符串函数更快

标签: vba excel


【解决方案1】:

我认为没有更简洁的方法可以做到这一点,因此您可以将其包装在一个函数中。另一种方法是使用replace,但它并不干净。

Function Insert(source As String, str As String, i As Integer) As String
    Insert = Replace(source, tmp, str & Right(source, Len(source)-i))
End Function 

或者只是修改你所拥有的

Function Insert(source As String, str As String, i As Integer) As String
    Insert = Mid(source, 1, i) & str & Mid(source, i+1, Len(source)-i)
End Function 

【讨论】:

  • 旧线程,但通过(ab)使用与 VBA.Replace 略有不同的WorksheetFunction.Replace 解决方案更简单/更优雅。我在下面的回答中举了一个例子
【解决方案2】:

这是已接受答案的版本,添加了测试并按照我期望的方式工作:

Function Insert(original As String, added As String, pos As Long) As String

    If pos < 1 Then pos = 1
    If Len(original) < pos Then pos = Len(original) + 1

    Insert = Mid(original, 1, pos - 1) _
                        & added _
                        & Mid(original, pos, Len(original) - pos + 1)

End Function

测试通过:

Public Sub TestMe()

    Debug.Print Insert("abcd", "ff", 0) = "ffabcd"
    Debug.Print Insert("abcd", "ff", 1) = "ffabcd"
    Debug.Print Insert("abcd", "ff", 2) = "affbcd"
    Debug.Print Insert("abcd", "ff", 3) = "abffcd"
    Debug.Print Insert("abcd", "ff", 4) = "abcffd"
    Debug.Print Insert("abcd", "ff", 100) = "abcdff"

End Sub

【讨论】:

    【解决方案3】:

    这是我这个问题的 50 美分。

    首先,我要感谢来自wmfexel 的WONG, Ming Fung 我发现了这个技巧。

    与要求替换字符串的 VBA Replace 函数不同,Replace 工作表函数只要求输入原始字符串中的位置和要覆盖的字符数。

    通过“滥用”这个覆盖参数,将其设置为 0 允许我们通过替换 0 个字符来在 Orignin 字符串的特定位置添加给定字符串。

    这里是它的工作原理:

    Dim test_date As String
    test_date = "01 / 25 / 995"
    test_date = Worksheetfunction.Replace(test_date, 11, 0, "1")
    'Now test_date = "01 / 25 / 1995" as we added "1" at the 11th position in it
    

    如您所见,它非常方便且易读。 对于那些挑剔并认为 Replace 这个名称只是令人困惑的人,将其包装在 Insert 函数中,您将完成;)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      相关资源
      最近更新 更多