处理不一致的字符串可能很棘手。这是一个可以确定匹配的姓氏和名字的首字母的函数,前提是字符串模式在您的示例之外没有变化。将其添加到模块中,然后您可以通过在单元格中输入公式 =AppendFileName 来访问它。
Public Function AppendFileName(ByVal LName As String, ByVal FName As String, ByVal FileName As String, ByVal AccN As String) As String
If LName = Left(FileName, Len(LName)) Then
If Mid(FileName, Len(LName) + 1, 1) = "," Then 'Check if the string contains a comma
If Mid(FileName, Len(LName) + 3, 1) = Left(FName, 1) Then
AppendFileName = FileName & " " & AccN
End If
Else 'If no comma then assume just one space
If Mid(FileName, Len(LName) + 2, 1) = Left(FName, 1) Then
AppendFileName = FileName & " " & AccN
End If
End If
End If
If AppendFileName = "" Then AppendFileName = False
End Function
您可以围绕此代码创建一个循环以遍历所有文件和名称并使用 dir 函数自动执行,例如。
Dim x as integer, DirFile as string
DirFile = Dir(Path)
Do While DirFile <> ""
x = x + 1 'To track how many files, and to assign variables as in below line of code
'Set each string variable like FName = Range("A1").offset(x,0).value
'Then assess the the names and file names with the If statements above
'Do something with appended FileName
DirFile = Dir
Loop
希望这可以帮助。