VBA文本循环优化 – 从文本中提取电子邮件

我需要一个小项目的帮助。 我刚开始使用VBA,我想我可以使用学习来优化我的代码。

单元格A2包含许多用“,”分隔的电子邮件地址的文本。 我设法提取所有的电子邮件地址,但我认为我使用了太多的单元格,而且我想知道是否可以帮助我减less它,并使用定义的variables。 工作代码的屏幕截图

Sub fpor() Dim Text As String Dim full As Integer Dim i As Integer Dim e As Integer Dim part As String Dim part_len As Integer Dim part_a As Integer Dim Text_2 As String x = 5 ActiveCell = Range("A2") Text = Range("A2") full = Len(Text) 'full = InStrRev(Text, ",") For i = 1 To full Cells((x + i), 1).Value = Text part = InStr(Text, ",") Cells((x + i), 2).Value = part Cells((x + i), 3) = Left(Text, part) Cells((x + i), 4) = full - part Text = Right(Cells((x + i), 1), Cells((x + i), 4)) If part = 0 Then full = 0 Cells((x + i), 3) = Text Exit For Else: full = Len(Text) End If Next i MsgBox (full) MsgBox (part) End Sub ` 

你如何看待我可以更好地优化For循环?

谢谢大家的回答你真棒人:)

您可以使用Split()函数大大简化您的代码,如下所示:

 Option Explicit Sub fpor() Dim emailsArr As Variant With Worksheets("emails") '<--change "emails" with your actual sheet name emailsArr = Split(.Range("a2"), ",") '<--| split all emails names delimited by a ',' into an array .Range("A6").Resize(UBound(emailsArr)).value = Application.Transpose(emailsArr) '<--| write array content from cell A6 downwards End With End Sub