VBA如何使用stringvariables循环instr函数?

我刚开始学习VBA,我正在尝试获得一个if和loop函数一起工作。 我基本上想在列A中search@,如果有@则=确定,如果不是=“无效”。 我得到它为一行工作,但循环它的整个列。 请提醒。 PS。 请放纵我的丑陋的第一个计时器代码。

克里斯汀先生,谢谢你

Sub help() Dim email As String email = InStr(email, "@") Do While email = InStr(email, "@") Cells(email, 1).Value = email If email = 0 Then Cells(email, 1).Offset(, 1).Value = "Not valid" Else Cells(email, 1).Offset(, 1).Value = "ok" End If Loop End Sub 

在这里输入图像说明

你可以设置一个范围,然后遍历该范围:

 Sub help() Dim email As String Dim rng As Range, cel As Range 'New Dim lastRow as Long 'New lastRow = Range("A"& rows.count).End(xlUp).Row Set rng = Range("A2:A" & lastRow) 'Adjust as necessary For Each cel In rng If InStr(1, cel.Value, "@") > 0 Then cel.Offset(0, 1).Value = "Ok" Else cel.Offset(0, 1).Value = "Not Valid" End If ' OR as @JohnyL points out, you can do the above in line. ' Just comment out/remove the above `If` statement and uncomment below ' cel.Offset(0, 1) = IIf(InStr(1, cel.Value, "@") > 0, "Ok", "Not Valid") Next cel End Sub 

这是一个超短的macros,可能工作,这取决于你的数据是如何布局的:

 Sub t() Dim rng As Range Set rng = Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row) rng.Offset(0, 1).Formula = "=IF(ISERR(SEARCH(""@"",A2)),""Not Valid"",""Yes"")" rng.Offset(0, 1).Value = rng.Offset(0, 1).Value End Sub 

或者,您可以创build一个用户定义的函数。 在工作簿模块中input以下代码:

 Function validate_email(cel As Range) As String If InStr(1, cel.Value, "@") > 0 Then validate_email = "Valid" Else validate_email = "Not Valid" End If End Function 

而在单元格中,说B20 ,只是=validate_email(A20) ,我会检查你。 这具有能够在任何单元上运行的优点,而不必编辑你的macros的范围。

在这里输入图像说明

另外,需要注意的是,您不需要VBA ,只需在列B中使用公式=IF(ISERR(SEARCH("@",A2)),"Not Valid","Yes")并拖动下。

最后,正如我在评论中提到的,这并不能真正检查电子邮件的有效性。 但是,对于你的问题,它的作品。 看到这个页面 ,或者这个页面 ,或者简单地searchVBA电子邮件validation以获取更多的方法来检查电子邮件地址是否正确。

A19开始,这是一个可能的解决scheme:

 Option Explicit Sub help() Dim email As String Dim rngCell As Range Set rngCell = Range("A19") Do While rngCell <> vbNullString If InStr(rngCell, "@") Then rngCell.Offset(, 1) = "Ok" Else rngCell.Offset(, 1) = "Not valid" End If Set rngCell = rngCell.Offset(1, 0) Loop End Sub 

如何做一个稍微不同的方式:

 Sub foo() Dim email As String Dim lastrow As Long lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'change the Sheet1 to whatever For i = 2 To lastrow 'loop through from row 2 to Last email = InStr(Sheet1.Cells(i, 1).Value, "@") 'do the Instr If email = 0 Then Sheet1.Cells(i, 2).Value = "Not Valid" If email > 0 Then Sheet1.Cells(i, 2).Value = "Ok" Next i End Sub 

你是在像下面的代码之后:

 Option Explicit Sub help() Dim LastRow As Long, i As Long LastRow = Cells(Rows.Count, "A").End(xlUp).Row ' get last row with data in column A For i = 1 To LastRow If InStr(Range("A" & i).Value2, "@") > 0 Then Range("B" & i).Value2 = "ok" Else Range("B" & i).Value2 = "Not Valid" End If Next i End Sub