【问题标题】:VBA text loop optimisation - Extract emails from textVBA 文本循环优化 - 从文本中提取电子邮件
【发布时间】:2016-08-27 09:27:15
【问题描述】:

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

单元格 A2,包含多个电子邮件地址的文本,以“,”分隔。我设法提取了所有电子邮件地址,但我认为我过多地使用了单元格,我想知道您是否可以帮助我减少它并使用定义的变量来代替。 Screenshot of the working code

 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 循环?

感谢大家的回答,你们这些了不起的人:)

【问题讨论】:

    标签: excel vba for-loop optimization


    【解决方案1】:

    使用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
    

    【讨论】:

    • 这很强大。谢谢 user3598756 ; ) 那个代码是邪恶的。
    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 2014-03-23
    • 2018-03-13
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多