下面我已经包含了当前的vba脚本,用于运行包含多个电子邮件的文件,这些电子邮件具有与电子邮件中讨论的地址更改相对应的特定文件名。我想从每个文件名中获取与地址更改有关的文本,并在excel表中输入新旧地址。此文件夹中的所有电子邮件分为4个类别,标题格式如下:以下是所有四个的示例:
正如你所看到的,它们都以相同的字符串开头#34;地址变更发行"但是我在获取可以适应所有这些不同场景的脚本时遇到问题。下面我已经包含了脚本的当前迭代如果任何人有任何建议或改进将非常有用,谢谢你。
Dim StrFile As String
'Change this to the directory containing all Address Change Circulation emails
'This will Pull in a list and, to the best of its ability make two columns that hold the data for
'the old and the new address
StrFile = Dir(Range("AddressChangeFolderPath").Value)
Dim Names() As String
Dim StrName
Do While Len(StrFile) > 0
CheckVal = InStr(1, StrFile, "Address Change Circulation -", vbTextCompare) + _
InStr(1, StrFile, "Address Change Circulation from ", vbTextCompare)
If CheckVal <> 1 Then 'if the email does not fit the standard, just place it in the cell and
'move on to the next entry
Selection.Value = StrFile
Selection.Interior.Color = RGB(255, 255, 0) 'highlight the cell
Selection.Offset(1, 0).Select
Else
StrName = Right(StrFile, Len(StrFile) - 29) 'trim to the correct size - probably not the
'best way to do this but it works
If Left(StrName, 4) = "from" Then
StrName = Right(StrName, Len(StrName) - 5)
ElseIf Left(StrName, 2) = "om" Then
StrName = Right(StrName, Len(StrName) - 3)
End If
StrName = Left(StrName, Len(StrName) - 4)
Changes = Split(StrName, " and ")
For Each Change In Changes
Names = Split(Change, " to ")
If Len(Names(0)) < 5 Then
Selection.Value = Names(0) & Right(Names(1), Len(Names(1)) - Len(Names(0)))
Else
Selection.Value = Names(0)
End If
If UBound(Names) >= 1 Then 'this is a zero indexed array, checking greater than or
'equal to 1 will check if there are two or more entries
Selection.Offset(0, 1).Value = Names(1) ' in the event that there is no " to " in
'the file name and it hasn't been handeled already
End If
Selection.Offset(1, 0).Select 'select the next cell to accept the next entry
Next
End If
loop
答案 0 :(得分:0)
根据您的示例,这可能是一种合理的方法。 如果将解析拆分为单独的方法,则更容易管理。
只需解析工作表中某个范围内的文本:
Sub Process()
Dim c As Range, op As String, np As String
For Each c In Range("A1:A6").Cells
ParseAddresses c.Value, op, np '<< passing np/op by reference...
c.Offset(0, 1).Value = op
c.Offset(0, 2).Value = np
Next c
End Sub
'Parse two addresses from "t" into "op" and "np"
Sub ParseAddresses(ByVal t, ByRef op As String, ByRef np As String)
Dim arr
op = "": np = ""
t = Trim(t)
If t Like "Address Change Circulation -*to*" Then
t = Replace(t, "Address Change Circulation -", "")
t = Replace(t, "from", "")
arr = Split(t, "to")
op = Trim(arr(0))
np = Trim(arr(1))
' "from" part is just a number: replace number in "to" part
If IsNumeric(op) Then
arr = Split(np, " ")
arr(0) = op
op = Join(arr, " ")
End If
End If
End Sub