我正在尝试编写一个代码来调用我拥有的各种私有子代码。如果在范围内找到某个国家/地区名称,我想调用sub。我的范围列在D列的一个名为“信息表”的表中。我将需要子运行遍历每个国家/地区,而不是在第一次匹配后停止。我在私有子代码中有代码来验证要做什么,只是根据范围标准调用它们是我正在努力的事情。
我认为我需要某种If“巴西”然后打电话... ElseIf“China”然后打电话给...
此外,如果第一个国家没有出现,我需要什么样的错误处理,我不希望宏停止运行,需要它循环遍历所有国家/地区。 (我举两个例子,大约20个)
非常感谢所有贡献者的时间和精力!
Sub Send_Email()
Dim Country As Range
Set Country = Worksheets("Info Table").Range("D3:D30").Text.Find("Brazil")
Call Email_Brazil
Set Country = Worksheets("Info Table").Range("D3:D30").Text.Find("China")
Call Email_China
End Sub
答案 0 :(得分:1)
我会这样做:
Sub Send_Email()
Dim country As String
Dim yourWorksheet As Worksheet
Set yourWorksheet = ThisWorkbook.Sheets("Info Table")
For j = 3 To 30
country = yourWorksheet.Range("D" & j)
Select Case country
Case "Brazil": Call Email_Brazil
Case "China": Call Email_China
Case "France": Call Email_France
End Select
Next j
End Sub
像这样,您将始终遍历所有单元格并仅在找到国家/地区时调用您的宏。此外,一旦您需要这样做,它将直接添加/删除潜艇。
答案 1 :(得分:1)
我不会为每个国家/地区设置单独的子目录。我会用一个函数发送你的所有电子邮件,如下所示:
Sub Send_Emails()
Dim ws As Worksheet
Dim country As Range
Dim cell As Range
Dim message As String
Set ws = Worksheets("Info Table")
Set country = ws.Range("D3:D30")
' loop through all cells in the range and email each
For Each cell In country
' in case you need to pass something other than
' the country to the email function
message = cell.Offset(, 2).Value2
Call SendEmailTo(cell.Value2)
Next cell
End Sub
Function SendEmailTo(country As String, message As String)
' rather than having a separate sub to send an email to each country
' use a function that accepts a country and send the email accordingly
' you now have access to both the country and
' the message (or modify to pass in whatever you need)
' The function should include boilerplate email code that all of the emails
' subs share, with a case statement for the parts that differ.
End Function
这有助于保持代码干净。 (Don't Repeat Yourself)