在Excel VBA字符串中插入内容

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)

有没有其他更简单/更优雅的方法来做到这一点?


2
使用 Mid$ 而不是 Mid,前者是字符串函数,后者是变体函数。字符串函数更快。 - brettdj
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 

旧的线程,但通过(滥用)WorksheetFunction.Replace 来实现更简单/更优雅的解决方案,它与 VBA.Replace 稍有不同。我在下面的答案中给出了一个例子。 - SomeDude

5

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

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

1
这是我对这个问题的建议。
首先,我需要感谢wmfexel的WONG,Ming Fung提供了这个技巧。
与VBA的Replace函数要求替换字符串不同,Replace工作表函数仅要求指定原始字符串中的位置和要覆盖的字符数。
通过“滥用”此覆盖参数,将其设置为0,我们可以通过替换0个字符来在特定位置添加给定字符串到原始字符串中。
以下是它的工作方式:
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函数中,您就完成了;) 。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接