如果find范围内的文本VBA调用子

我试图写一个代码,调用各种私人潜艇我有。 如果在范围内find某个国家/地区名称,我想调用一个子。 我的范围列在D列中的一个名为“信息表”的表格中。我将需要这个子表格在每个国家运行,而不是在第一场比赛之后停止。 我有在私人潜艇的代码来validation该怎么做,只是基于范围标准调用他们是我奋斗的东西。

我假设我需要某种如果“巴西”然后打电话…其他如果“中国”那么打电话…

另外,如果第一个国家不出现,我需要什么样的error handling,我不希望macros停止运行,需要它遍历所有的国家。 (我举两个例子,大约有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 

我会这样做:

 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 

就像这样,你将永远遍历你的所有单元格,并且只有在find了国家时才调用你的macros。 此外,一旦你需要这样做,它将会直接添加/删除子目录。

我不会为每个国家有一个单独的子。 我会用一个函数来发送你所有的电子邮件,例如:

 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 

这将有助于保持您的代码干爽。 ( 不要重复自己 )