vba VBA只在空格之前保留单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25257387/
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
VBA to only keep cell value before space
提问by foofuufuu
It seemed like a simple code but I couldn't find it anywhere on the net & I don't know how to write it.
这似乎是一个简单的代码,但我在网上的任何地方都找不到它,而且我不知道如何编写它。
What I want to do is that, say, cell range A1 has a value of "Hey ho he ha". What I want the code to do is to remove away the rest of the word after the 1st space, so what's left will be with only "Hey".
我想要做的是,比如说,单元格区域 A1 的值为“嘿嘿嘿”。我希望代码做的是删除第一个空格后的其余单词,所以剩下的将只有“嘿”。
Thanks!
谢谢!
回答by Siddharth Rout
One line Code...
一行代码...
Range("A1").Value = Split(Range("A1").Value, " ")(0)
Range("A1").Value = Split(Range("A1").Value, " ")(0)
Another one line code (based on IolandaAB's answer)
另一行代码(基于 IolandaAB 的回答)
If InStr(1, Range("A1").Value, " ") Then Range("A1").Value = Mid(Range("A1").Value, 1, InStr(1, Range("A1").Value, " ") - 1)
If InStr(1, Range("A1").Value, " ") Then Range("A1").Value = Mid(Range("A1").Value, 1, InStr(1, Range("A1").Value, " ") - 1)
And yet another one line code
还有另一行代码
If InStr(1, Range("A1").Value, " ") Then Range("A1").Value = Left(Range("A1").Value, InStr(1, Range("A1").Value, " ") - 1)
If InStr(1, Range("A1").Value, " ") Then Range("A1").Value = Left(Range("A1").Value, InStr(1, Range("A1").Value, " ") - 1)
Take your pick :) My favorite is still the first one.
随便选:) 我最喜欢的仍然是第一个。
回答by AdrIB
Sub extract()
Dim myString As String, lung As Integer, i As Integer, pos As Integer
myString = Range("A1").value
lung = Len(myString)
For i = 1 To lung
pos = InStr(i, myString, " ")
If pos <> 0 Then
Exit For
End If
Next i
Range("A1").value = Mid(myString, 1, pos)
End Sub
Loop through the value from your cell and exit when the first space is found in your text. Extract the text before the found space and copy this in your cell.
循环遍历单元格中的值并在文本中找到第一个空格时退出。提取找到的空间之前的文本并将其复制到您的单元格中。