Excel宏条件格式化间接单元格

时间:2012-06-13 18:01:10

标签: excel excel-vba conditional-formatting vba

我对Excel有点缺乏经验,但我会尽力解释我想要做的事情:

我正在使用Excel 2010,我正在尝试让宏根据列中的数字进行添加。

例如,我想让宏根据B列中的名称和C列中的数字添加值。对于B列中的名称“02 Gloves-DISC”,我想根据C列中的值添加以下内容:如果它是< 5,+ 8.83。如果它是< 10,+ 7。如果它是< 20,+ 5。如果它是< 30,+ 3。如果它是< 40,+ 1。如果它是< 56,+ 50。

我有类似的东西,但我无法让它为每一行进行搜索和计算:

Selection.Replace What:="02 Gloves-DISC", Replacement:="=IF(C2<5, C2+8.83, IF(C2<10, C2+7, IF(C2<20, C2+5, IF(C2<30, C2+3, IF(C2<40, C2+1, C2+.5)))))", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

我希望此信息有所帮助。预先感谢您的任何帮助。我已经读过有关R1C1的参考资料,但我似乎无法让它工作。

以下是我正在使用的数据示例:

SKU         ClassName           TakeItPrice
HJC10569002 02 Gloves-DISC          38.93
HJC1222066  02 Gloves-DISC          49.491
HJC1224011  02 Gloves-DISC          40.491
HJC1228062  02 Gloves-DISC          36.991
HJC152100   01 First Class-DISC 13.191
HJC152200   01 First Class-DISC 26.99
HJC152202   01 First Class-DISC 31.491
HJC180000   01 First Class-DISC 11.891
HJC190005   01 First Class-DISC 11.891
HJC350005   01 First Class-DISC 11.891

1 个答案:

答案 0 :(得分:0)

两个宏...第二个是我用来查找工作表中最后一行数据的通用宏。

Public Sub addDisc()
   Dim Class As Long
   Dim Price
   Dim myRow

   For myRow = 2 To xlLastRow(ActiveSheet.Name)   'Optional to find last row
     Class = CLng(Left(Cells(myRow, 2), 2))
     If Class < 5 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 8.83
     ElseIf Class < 10 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 7
     ElseIf Class < 20 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 5
     ElseIf Class < 30 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 3
     ElseIf Class < 40 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 1
     ElseIf Class < 56 Then
        Cells(myRow, 3) = Cells(myRow, 3) + 0.5
     End If
   Next myRow
End Sub


Public Function xlLastRow(Optional WorksheetName As String) As Long
   '    find the last populated row in a worksheet
   If WorksheetName = vbNullString Then WorksheetName = ActiveSheet.Name
      With Worksheets(WorksheetName)
        On Error Resume Next
        xlLastRow = .Cells.Find("*", .Cells(1), xlFormulas, _
        xlWhole, xlByRows, xlPrevious).Row
        If Err <> 0 Then xlLastRow = 0
      End With
End Function