[英]Setting Excel cell value based on another cell value using VBA
I have the following spreadsheet.我有以下电子表格。 When ever there is an x in cell BI need to populate the d and e cells in the same row using an equation I have.
当单元格中有 x 时,BI 需要使用我的方程式填充同一行中的 d 和 e 单元格。 if there is no x in the b cell I need to manually enter values into cells d & e.
如果 b 单元格中没有 x,我需要手动将值输入单元格 d 和 e。
How do I make my code non-row specific?如何使我的代码非行特定?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim val As String
val = Range("B3").Value
If val = "x" Then
Range("E3").Value = Range("d2").Value * Range("G2").Value
Range("D3").Value = Range("D2").Value
End If
End Sub
I'm not sure if I understand correctly, but if you have a parameter: row = 3 you can use Range("E" & row) instead of Range("E3").我不确定我是否理解正确,但是如果你有一个参数:row = 3 你可以使用 Range("E" & row) 而不是 Range("E3")。
Put a loop around that where you vary 'row' for the rows you want to modify.在你想要修改的行改变“行”的地方放一个循环。
Hope that helps!希望有帮助!
You've created a sub procedure around the Worksheet_SelectionChange event.您已经围绕 Worksheet_SelectionChange 事件创建了一个子过程。 In fact, you require Worksheet_Change and you need to,
事实上,你需要 Worksheet_Change 并且你需要,
Rewrite:改写:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B:B")) Is Nothing Then
On Error GoTo safe_exit
Application.EnableEvents = False
Dim t As Range
For Each t In Intersect(Target, Range("B:B"))
If LCase(t.Value) = "x" Then
'I've made these formulas relative to each target
'you may want to make some absolute references
t.Offset(0, 3) = t.Offset(-1, 2) * t.Offset(-1, 5)
t.Offset(0, 2) = t.Offset(-1, 2)
Else
t.Offset(0, 2).resize(1, 2) = vbnullstring
End If
Next t
End If
safe_exit:
Application.EnableEvents = True
End Sub
Please try below code.请尝试以下代码。 It loop through all non empty rows in column B and check if there is value: x If so it populate your formulas.
它遍历 B 列中的所有非空行并检查是否有值:x 如果有,它会填充您的公式。
Sub new_sub()
' get last_row of data
last_row = ActiveSheet.UsedRange.Rows.Count
' loop through all rows with data and check if in column B any cell contains value: x
For i = 1 To last_row
' if there is any cell with value: x
' then add below formulas
If Cells(i, 2).Value = "x" Then
' for column E: take value from row above for col D and G and multiple
Range("E" & i).Value = Range("d" & i - 1).Value * Range("G" & i - 1).Value
' for column D: take value from row above
Range("D" & i).Value = Range("D" & i - 1).Value
End If
Next i
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.