您可以在名称、城市和国家/地区之间设置一些分隔符,例如:ABCD:New Delhi:India。有分隔符可以让你分隔名称、城市和国家。现在您可以轻松确定每个字符串的长度。现在根据您的要求,您可以轻松地编辑数据并写入文件。您可以参考以下代码以供参考:文本文件:exceltest abcd:new delhi:india test:NY:USA
宏代码:
Sub readTextFile()
Dim oFSO As New FileSystemObject
Dim oFS
Dim objFSO As New FileSystemObject
Set myTemp = objFSO.CreateTextFile("C:\Users\Rohit\Desktop\exceltestTemp.txt", True)
Set oFS = oFSO.OpenTextFile("C:\Users\Rohit\Desktop\exceltest.txt")
Do Until oFS.AtEndOfStream
stext = oFS.ReadLine
Dim testarray() As String
testarray = Split(stext, ":")
Dim i As Integer
i = Len(testarray(0)) 'determine length of each String, here as a sample only length of one string is determined
Cells(4, "a").Value = i 'writing a length to excel sheet, you can write to any location
Cells(1, "a").Value = testarray(0) 'writing contents to excel sheet
Cells(2, "a").Value = testarray(1) 'writing contents to excel sheet
Cells(3, "a").Value = testarray(2) 'writing contents to excel sheet
'Search for the Name
If testarray(0) = "test" Then
testarray(1) = "Mumbai"
End If
myTemp.WriteLine testarray(0) & ":" & testarray(1) & ":" & testarray(2) 'writing to a temp text file
Loop
End Sub
现在根据您的要求,您可以搜索名称并编辑数据并写入文件。然后您可以删除原始文件并将临时文件保存为原始文件。
PS:在 Excel 2007 上试过。您需要添加参考“Microsoft Scripting Runtime”。