我有一个包含数十个/数百个不同名称的列,其中一些列出了多次。每个名称的格式都是firstname.lastname。我需要拆分它们才能正确列为名字姓氏。使用split函数,通常第一个参数是您需要拆分的字符串。
我之前使用过这个要分割的项目数组,但我总是要列出数组中的每个项目。当然,这不可能有数百个不同的名字。
我已经搜索过了,但我找到的每个答案总是使用数组,或者正在讨论如何拆分成多列。
如何编写代码以便代码遍历整个列(在本例中为B)并拆分每个名称,同时保留一列中的所有内容?
代码如下:
nameSplit = Split(all_names_in_column_B, ".")
答案 0 :(得分:3)
选择列,按控制按钮和F以显示查找和替换,查找“。”并替换输入空格(通过按空格键一次)。假设您在包含句点的单元格中没有其他文本。
你可以在VBA中做同样的事情。
Sub TEST()
ActiveSheet.Columns("A").Replace _
What:=".", Replacement:=" ", _
SearchOrder:=xlByRows, MatchCase:=False
End Sub
答案 1 :(得分:0)
执行此操作的代码如下所示
Public Sub SplitTest()
Dim ws As Worksheet 'Declare a worksheet variable
Dim sheetName As String: sheetName = "Sheet1" 'Provide the name of the sheet where the data is located
Set ws = ActiveWorkbook.Sheets(sheetName) 'Assign it to the worksheet variable
Dim inputRng As Range 'Declare a range variable
Dim rangeName As String: rangeName = "B1:B5" 'Assign the range location using whatever method you like to select your range
Set inputRng = ws.Range(rangeName) 'Assign the range to the range variable
Dim splitStringArray() As String 'Declare a variable length array of strings to hold the result of the split
Const FirstName = 0 'FirstName is element 0 of splitStringArray
Const LastName = 1 'LastName is element 1 of splitStringArray
Dim enumRng As Range 'Declare a range variable to be used as an enumerator
For Each enumRng In inputRng 'Loop through the range one cell at a time
splitStringArray = Split(enumRng, ".") 'Split the value located in the cell
enumRng.Value2 = splitStringArray (FirstName) & " " & splitStringArray (LastName) 'Overwrite the value in the current cell with the First and Last Names
'separeated by a space, this could be anything
Next enumRng
End Sub