VBA - 从值会改变的单元格中存储值的最佳方式
VBA - best way of storing value from cell whose value will change
我在单元格 b2 中有一个公式,它会根据宏的输入而改变。在某个时间点存储 b2 值的最佳方法是什么?
宏将被调用多次,我不知道是否可以将值(从那个时间点开始)存储为变量,而不会在每次调用宏时都被覆盖。我将值存储在一个单元格中,想知道是否有更好的方法...
'stores index value
If IsEmpty(Sheet30.Range("AU9")) = False Then
Else
Sheet30.Range("AU9").Value = Sheet30.Range("b2")
End If
'followed by code that changes the value of cell b2
这就是我在实际电子表格中存储值的方式。同样,宏会被用户多次调用,我想存储b2的第一个迭代值。有没有更有效的方法?
编辑:
我修改了 Mukul 的答案,以便可以多次调用它。
Public Sub PreserveFirstValue(n as variant, o as range, p as boolean)
If Not p Then
If isnumeric(o.value) then
n = o.value
p = True
End If
End If
End Sub
- 向工作簿添加一个模块并声明一个 public 布尔值和一个 public 变量以保留旧值。
- 在工作簿打开后立即保留单元格的值(即 Private Sub Workbook_Open() 事件),或者您觉得是时候在您正在执行的代码中保留单元格的值现在。
代码如下:-
'Place below statement where you want to preserve the value
Call PreserveFirstValue() 'add this line to preserve the value
'Module Code is below
Public HasPreservedValue As Boolean
Public OldValue As String
Public Sub PreserveFirstValue()
If Not HasPreservedValue Then
OldValue = Sheet30.Range("b2").Text
HasPreservedValue = True
End If
End Sub
我在单元格 b2 中有一个公式,它会根据宏的输入而改变。在某个时间点存储 b2 值的最佳方法是什么?
宏将被调用多次,我不知道是否可以将值(从那个时间点开始)存储为变量,而不会在每次调用宏时都被覆盖。我将值存储在一个单元格中,想知道是否有更好的方法...
'stores index value
If IsEmpty(Sheet30.Range("AU9")) = False Then
Else
Sheet30.Range("AU9").Value = Sheet30.Range("b2")
End If
'followed by code that changes the value of cell b2
这就是我在实际电子表格中存储值的方式。同样,宏会被用户多次调用,我想存储b2的第一个迭代值。有没有更有效的方法?
编辑: 我修改了 Mukul 的答案,以便可以多次调用它。
Public Sub PreserveFirstValue(n as variant, o as range, p as boolean)
If Not p Then
If isnumeric(o.value) then
n = o.value
p = True
End If
End If
End Sub
- 向工作簿添加一个模块并声明一个 public 布尔值和一个 public 变量以保留旧值。
- 在工作簿打开后立即保留单元格的值(即 Private Sub Workbook_Open() 事件),或者您觉得是时候在您正在执行的代码中保留单元格的值现在。
代码如下:-
'Place below statement where you want to preserve the value
Call PreserveFirstValue() 'add this line to preserve the value
'Module Code is below
Public HasPreservedValue As Boolean
Public OldValue As String
Public Sub PreserveFirstValue()
If Not HasPreservedValue Then
OldValue = Sheet30.Range("b2").Text
HasPreservedValue = True
End If
End Sub