VBA字段更新

时间:2014-05-18 21:37:07

标签: excel-vba range updates vba excel

我有一张表格,其中有5列

Row  OM    MA    HP      D 
----------------------------------    
1    212   5454  4787    OM
----------------------------------
2    212   5454  4787    MA
----------------------------------
3    212   5454  4787    OM
---------------------------------
4    212   5454  4787    HP
--------------------------------

我想根据D中的值更新OM,MA和HP。所以如果D = OM我想让除OM之外的列等于零。

我已经编写了脚本,但我想学习如何更改此脚本,以便脚本选择的范围是动态的,而不是事先指定的,并且可以根据我们拥有的数据进行更新。

有人可以帮我吗?

提前致谢,

这是脚本:

Public Sub DataClear()

Dim rgdata As Range
Dim i As Integer

Worksheets("Data").Activate
Set rgdata = Range("A1:E10")
For i = 0 To rgdata.Rows.Count
    If rgdata.Cells(i + 1, "E").Value = "MO" Then
        rgdata.Cells(i + 1, "C").Value = "0"
        rgdata.Cells(i + 1, "D").Value = "0"
    ElseIf rgdata.Cells(i + 1, "E").Value = "MA" Then
        rgdata.Cells(i + 1, "B").Value = "0"
        rgdata.Cells(i + 1, "D").Value = "0"
    ElseIf rgdata.Cells(i + 1, "E").Value = "HP" Then
        rgdata.Cells(i + 1, "B").Value = "0"
        rgdata.Cells(i + 1, "C").Value = "0"
    End If
Next i

End Sub

3 个答案:

答案 0 :(得分:1)

您希望使用MATCH function查看 - 当您使用OMHP的范围调用它时,并在D列中搜索值,它会为您提供所需的偏移量。

您可能会考虑的其他事项:按行逐步执行数据。

示例:

For Each rr in rgdata.Rows
  goodCol = Application.Worksheetfunction.Match(rr.cells(1, lookupCol))
  for ii = 1 To lookupCol - 1
    if ii <> goodCol Then rr.cells(1,goodCol)=0
  next ii
next rr

答案 1 :(得分:1)

如果您使用

LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

您将找到包含数据的最后一行。然后您可以将set语句修改为

Set rgdata = Range("A1:E" & LastRow)

答案 2 :(得分:1)

我也是我......

Option Explicit
Public Sub DataClear()

Dim Counter As Long, LastRow As Long
Dim DataSheet As Worksheet

'set references, loop boundary and range
Set DataSheet = ThisWorkbook.Worksheets("Data")
With DataSheet
    LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End With

'use case statement and for loop to evaluate
With DataSheet
    For Counter = 1 To LastRow
        Select Case .Cells(Counter, 5).Value
        Case Is = "OM"
            .Cells(Counter, 3) = 0
            .Cells(Counter, 4) = 0
        Case Is = "MA"
            .Cells(Counter, 2) = 0
            .Cells(Counter, 4) = 0
        Case Is = "HP"
            .Cells(Counter, 2) = 0
            .Cells(Counter, 3) = 0
        Case Else
        End Select
    Next Counter
End With

End Sub

上面的脚本使用的技术类似于上面使用的技术(虽然我认为你的代码有一个拼写错误,你正在寻找“MO”而不是“OM”)并结合以下技术: