VBA:覆盖具有多个IF条件的单元

时间:2016-02-25 10:25:03

标签: excel vba excel-vba

我想编写一个VBA宏来在满足两个条件时给出一个特定的值,但我似乎无法找到一种方法来做到这一点,并且搜索并没有帮助我具体问题。

以下是问题的快速摘要:

如果其他两个单元格中的值与特定单元格匹配,我想覆盖特定单元格中的值。

我有一个相同报告的工作代码,如果另一个值与特定内容匹配,则覆盖一个值,这里是代码:

Sub test_overwrite()

Dim msheet As Worksheet

Set msheet = ActiveSheet

'Overwrites for test and reactivated cells

  For i = 2 To msheet.UsedRange.Rows.Count
   Select Case msheet.Cells(i, 7)
   Case Is = "test"
    msheet.Cells(i, 5) = "test"
   Case Is = "reactivated"
    msheet.Cells(i, 5) = "reactivated"
   End Select

Next i

End Sub

基本上,我想要添加到此代码中的是能够覆盖(i,7)中的单元格,如果(i,5)的值匹配" expired"并且(i,6)的值匹配" #N / A"。

我该怎么做?

编辑1:

这是我刚刚尝试过的东西,但是我得到了一个“需要对象”#39;错误

Sub subs_test_new_tests()

'Mark certain fields that are 'expired' as 'test'

Dim msheet As Worksheet
Dim state As String
Dim match As String
Dim status As String

Set msheet = ActiveSheet

For i = 2 To msheet.UsedRange.Rows.Count

Set state = msheet.Cells(i, 5)
Set match = msheet.Cells(i, 6)
Set status = msheet.Cells(i, 7)

If state = "expired" And match = "#N/A" Then
status = "test"

End If

Next i

End Sub

2 个答案:

答案 0 :(得分:0)

试试这个:

Sub test_overwrite()
Dim msheet As Worksheet
Set msheet = ActiveSheet
With msheet
'Overwrites for test and reactivated cells
  For i = 2 To .UsedRange.Rows.Count

   Select Case Trim(.Cells(i, 7).Text)

   Case Is = "test"
      Trim(.Cells(i, 5).Text) = "test"
   Case Is = "reactivated"
      Trim(.Cells(i, 5).Text) = "reactivated"
   End Select

   if Trim(.Cells(i, 5).Text) = "expired" And  ISERROR(.Cells(i, 6)) then  .Cells(i, 7) = "test"

Next i
End With
End Sub

答案 1 :(得分:0)

Sub subs_test_new_tests()

With ActiveSheet
    For i = 2 To .UsedRange.Rows.Count
        If .Cells(i, 5) = "expired" Then
            If .Cells(i, 6) = "#N/A" Or Application.IsNA(.Cells(i, 6)) Then
                .Cells(i, 7) = "test"
            End If
        End If
    Next i
End With

End Sub