删除Excel VBA中第二个空格之后的文本

我试图做一个macros来导出一列名称(列A)到.csv

例子,

  1. 玛丽简
  2. THOMAS LEE
  3. 瑞恩·克里斯托弗·史密斯

我想做的只是把名字的前两个部分,因为有些名字有超过3个部分,所以它最终这样

  1. 玛丽简
  2. THOMAS LEE
  3. RYAN CHRISTOPHER

我可以用正常的单元格function来完成,但是我似乎无法使它与VBA一起工作。

您可以使用Instr从指定的起点findstring中的字符。 所以使用它两次,第一次find位置后第二次开始

 Function TwoWords(str As String) As String Dim i As Long ' remove any multiple or leading /trailing spaces str = Application.WorksheetFunction.Trim(str) ' locate 2nd space if it exists i = InStr(str, " ") If i > 0 Then i = InStr(i + 1, str, " ") If i > 0 Then str = Left$(str, i - 1) End If End If TwoWords = str End Function Sub Demo() Dim str As String ' For Demo str = TwoWords("RYAN CHRISTOPHER SMITH") Debug.Print str str = TwoWords("THOMAS LEE") Debug.Print str End Sub 

在即时窗口中查看Demo的结果