VBA 多个条件的宏检查范围

VBA Macro Checking range for multiple Criteria

我写了一个宏来检查一个值的选择,如果它适合那个值,用其他东西替换它。好的,当它只有一个值时,这很容易。当我尝试添加多个值时,我将 运行 保留为不同的错误。希望你们中的一个能指出我遗漏的地方:)

 Sub PTranslate()
 Dim cell As Range
 On Error Resume Next
 For Each cell In Selection
 If cell = "DZC" Or "0654548" Then
 cell.Value = "Douglas C"
      ElseIf cell = "RLP" Or "0623344" Then
 cell.Value = "Ryan P"
 End If
 Next


 End Sub

简短的回答是这样的。正确的语法是在多个条件 If 语句中每次 引用对象

 Dim cell As Range, sVal as String

 For Each cell In Selection

    sVal = Cstr(cell.Value2)

    If sVal = "DZC" Or sVal = "654548" Then 'sVal = "0654548" Then
        cell.Value = "Douglas C"
    ElseIf sVal = "RLP" Or sVal = "623344" Then 'sVal = "0623344" Then
        cell.Value = "Ryan P"
    End If

 Next

如果您要有很多查找值,最好在工作簿中列出一个列表,然后用查找列表中的关联值替换单元格值。您也可以使用 Select Case,但如果有 ~ 300 个选项,那甚至会很丑陋。

假设您在范围 A1:B300 的 mySheet 中构建列表,其代码为:

Dim cell As Range

 For Each cell In Selection

    If Not IsErr(Application.WorksheetFunction.VLookup(cell.Value2, Sheets("mySheets").Range("A1:B300"), 2, 0)) Then

        cell.Value = Application.WorksheetFunction.VLookup(cell.Value2, Sheets("mySheets").Range("A1:B300"), 2, 0)

    End If

 Next

对长列表使用'Select Case':

For Each cell In Selection
    Select Case cell.Value
        Case "DZC", "0654548"
             cell.Value = "Douglas C"
        Case "RLP", "0623344"
             cell.Value = "Ryan P"
        ...
        Case Else
             ...
     End Select
Next cell