10

在 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)

还有另一种更简单/更优雅的方法吗?

4

3 回答 3

14

我认为没有更清洁的方法可以做到这一点,因此您可以将其包装在一个函数中。另一种方法是使用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 
于 2013-05-17T20:49:18.610 回答
3

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

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
于 2018-06-20T13:29:15.523 回答
1

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

首先,我要感谢 wmfexel的 WONG, Ming Fung发现这个技巧的地方。

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

通过“滥用”这个覆盖参数,将其设置为 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 函数中,你就完成了;)。

于 2021-05-21T10:09:41.687 回答