VBA 如何使用字符串变量循环 instr 函数?

标签 vba excel

我刚刚开始学习 VBA,我正在尝试让 if 和循环函数一起工作。 我基本上想在A列中搜索@,如果有@则= ok,如果没有=“无效”。 我让它适用于一行,但适用于整列。请各位指教。 附注请纵容我丑陋的新手代码。

预先感谢您, 克里斯汀

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

enter image description here

最佳答案

您可以设置一个范围,然后循环该范围:

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

这是一个可能有效的超短宏,具体取决于数据的布局方式:

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

或者,您可以创建用户定义函数。在工作簿模块中输入此代码:

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),我会为您检查。这样做的优点是可以在任何单元格上运行,而不必编辑宏的范围。

enter image description here

此外,请注意,您不需要 VBA,只需使用公式 =IF(ISERR(SEARCH("@",A2)),"无效”,"is") 在 B 列中并向下拖动。

最后,正如我在评论中提到的,这并不能真正检查电子邮件的有效性。不过,对于你的问题,它是有效的。请参阅this page ,或this one ,或者直接搜索VBA email validation了解更多检查电子邮件地址是否正确的方法。

关于VBA 如何使用字符串变量循环 instr 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47758390/

相关文章:

VBA Excel 宏根据多个条件更新单元格值

excel - 更改部分 excel 公式以包含来自另一个单元格的数据

vba - VBA方法中 `:=`语法的含义

Excel宏很慢,有很多工作表

如果列中没有日期,则 read.xlsx 读取日期错误

vba - 当多个项目一次添加到 Outlook 文件夹时,如何触发事件?

vba - Excel VBA 问题 - If then ElseIf 语句

sql - Microsoft Access 找不到字段 '|1'

excel - 有条件复制粘贴

ms-access - 声明和调用 Sleep API