vba VBA中的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6052337/
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 11:30:58  来源:igfitidea点击:

Substring in VBA

stringexcelvbasplit

提问by S..

I have multiple strings in different cells like

我在不同的单元格中有多个字符串,例如

CO20:  20 YR CONVENTIONAL
FH30:  30 YR FHLMC
FHA31   

I need to get the substring from 1 to till index of ':' or if that is not available till ending(in case of string 3). I need help writing this in VBA.

我需要将子字符串从 1 到直到 ':' 的索引,或者如果它在结束之前不可用(在字符串 3 的情况下)。我需要帮助用 VBA 写这个。

回答by Tim Williams

Shorter:

更短:

   Split(stringval,":")(0)

回答by Steve Mallory

Test for ':' first, then take test string up to ':' or end, depending on if it was found

首先测试 ':',然后将测试字符串带到 ':' 或结束,具体取决于是否找到

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

回答by Pepe

You can first find the position of the string in this case ":"

在这种情况下,您可以先找到字符串的位置“:”

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

然后使用 Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)