我创建了VBA代码来应用公式,该公式应执行以下操作:当用户选择一个单元格区域时,该公式将应用于所选数据右侧的3列。例如,如果用户选择范围G8:G18,则在执行宏时,该公式应从范围G8:G18的数据应用于范围J8:J18
但是该公式位于G8范围内,而不是应用于J8:J18范围。
Sub ghjkk()
Dim c As Range
Dim rng As Range
Set rng = Selection.Offset(0, 3)
For Each c In rng
ActiveCell.FormulaR1C1 = _
"=IF(RC[-3]=0.2,""Y5"",IF(RC[-3]=0.1,""Y6"",IF(RC[-3]=0,""V0"",IF(RC[-3]=0.021,""Y3"",IF(RC[-3]=0.055,""Y4"",FALSE)))))"
Next c
End Sub
答案 0 :(得分:4)
尝试
Sub ghjkk()
Dim c As Range
Dim rng As Range
Set rng = Selection.Offset(0, 3)
For Each c In rng
c.FormulaR1C1 = _
"=IF(RC[-3]=0.2,""Y5"",IF(RC[-3]=0.1,""Y6"",IF(RC[-3]=0,""V0"",IF(RC[-3]=0.021,""Y3"",IF(RC[-3]=0.055,""Y4"",FALSE)))))"
Next c
End Sub
答案 1 :(得分:1)
如果需要,请更改工作表名称和范围,并在特定工作表的Worksheet_Change事件上导入以下代码。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("G8:G18")) Is Nothing Then
Application.EnableEvents = False
If Cells(Target.Row, 4).Value = "0.2" Then
Cells(Target.Row, 10).Value = "Y5"
ElseIf Cells(Target.Row, 4).Value = "0.1" Then
Cells(Target.Row, 10).Value = "Y6"
ElseIf Cells(Target.Row, 4).Value = "0" Then
Cells(Target.Row, 10).Value = "V0"
ElseIf Cells(Target.Row, 4).Value = "0.021" Then
Cells(Target.Row, 10).Value = "Y3"
ElseIf Cells(Target.Row, 4).Value = "0.055" Then
Cells(Target.Row, 10).Value = "Y4"
Else: Cells(Target.Row, 10).Value = "False"
End If
Application.EnableEvents = True
End If
End Sub