应用公式,从所选单元格偏移三列
Apply formula, offset three columns from selected cells
我创建了 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
尝试
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
如果需要,更改 sheet 名称和范围,并在特定 sheet 的 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
我创建了 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
尝试
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
如果需要,更改 sheet 名称和范围,并在特定 sheet 的 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