插入 Excel VBA 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16617366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:38:14  来源:igfitidea点击:

Inserting into an Excel VBA string

excelvbaexcel-vba

提问by George

In JAVA or C++, we can do something along the line of myString.insert(position, word). Is there a way we can do the same in Excel VBA's string? In my worksheet, I have a string looks like this: 01 / 01 / 995, I wants to insert a 1 into the year, so make it 01 / 01 / 1995.

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

Is there another easier / more elegant way to do it?

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

回答by T I

I dont think there is a cleaner way of doing it so you could just wrap it up in a function. Another way of doing it would be with replace, but it's not any cleaner.

我不认为有一种更简洁的方法可以做到这一点,因此您可以将其包装在一个函数中。另一种方法是使用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 

or just modify what you have

或者只是修改你所拥有的

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 

回答by Vityata

This a version of the accepted answer, with added tests and working the way I would expect it to work:

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

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

The tests pass:

测试通过:

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