我想通过引用另一个单元格范围中的条件将一个范围内的正值单元格输入更改为负值。因此,例如单元格范围 A1:A10 包含值“B”或“S”。单元格区域 B1:B10 是输入数值的位置。根据已在相应单元格 A1:A10 中输入的数据,输入这些值时将其设为正值或负值。因此,在 B1 中输入任何正值或负值作为 1234 或 -1234,其中 A1 的值为“B”将导致 B1 显示 -1234。相反,如果在单元格 B1:B10 中输入任何正值或负值,并且 A 列中相应行的值为“S”,则 B 列中的值将始终为正值,无论原始输入是负值还是正值。
如果 A1:A10 范围内的特定单元格中没有值对应于 B 列中的同一行,则应向用户显示一条消息,说“请在 A 列的相应行中输入一个值。
我是 VBA 编码的新手,到目前为止,其他帖子已经拼凑了以下代码,但我不知道如何完成它才能成功工作。
任何帮助将不胜感激。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A1 As Range
Set A1 = Range("A1:A10")
Dim A2 As Range
Set A2 = Range("B1:B10")
If Intersect(Target, A2) Is Nothing Then Exit Sub
If IsText(Target, A1) Then
If A1 = "S" Then
Application.EnableEvents = False
B1 = -B1
Application.EnableEvents = True
End If
End Sub
最佳答案
这应该是您需要的:For
循环允许您更改多个列 乙一次的值。如果列 一个 值既不是“B”也不是“S”,不采取任何行动。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim B As Range, Intersection As Range, cell As Range
Dim v As String
Set B = Range("B1:B10")
Set Intersection = Intersect(Target, B)
If Intersection Is Nothing Then Exit Sub
Application.EnableEvents = False
For Each cell In Intersection
v = cell.Offset(0, -1).Value
If v = "B" Then
cell.Value = -Abs(cell.Value)
ElseIf v = "S" Then
cell.Value = Abs(cell.Value)
End If
Next cell
Application.EnableEvents = True
End Sub
关于excel - 根据另一个单元格中的条件将正数值单元格输入更改为同一单元格中的负数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62372089/