如果值小于旧值,我如何清除列并再次填充数据 |excel|VBA|

用户11521067

我有一个 Excel

第 1 页

表 1

第 2 页

表 2

Sheet 1 的值 => F5 => '50' => 在 Sheet 2 中引用 => E4 => '50'

当我在工作表 1 中输入值代替 F5 => 值在工作表 2 中得到更改 => E4 => 自动

使用下面的代码数据被打印多次我的代码

模块: mac

Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column).End(xlUp))
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount) = sValue

End Sub

表 1 代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Sheets("Sheet1").Range("F5"), Target) Is Nothing Then
       Call mac
    End If
End Sub

这是输出

像下面这样的输出:

https://paste.pics/494c856d2908a83ca031ee20bb706a09

我上面的代码根据上面提到的输出完美运行,但其中存在一些缺陷

认为

条件 1:

如果输入的值为 '50' => 那么列“I”和“J”中的数据将打印 50 次 => 正确 [完美]

条件 2:

if the value entered is '60' => then data in the Coulmn "I" and "J" gets appends with the previous data which it as "50" => 50 + 10 => 60 => this is right [perfect]

Condition 3:

Assume the Column "I:J" already as DATA => upto the Range '60' if the entered value is less then '60' like '30' then updation should happen only 30 times in Column "I:J" the Data should be Printed But Nothing is happening appending happens but clearing data does not happen if range is lesser then old value

There as to be some mechanism like

if Count is 50 => print => I,J

if Count is more then 50 => append I,J

if Count is less then 50 => clear column I,J and then => fill the Column I ,J

How do i achieve this mechanism?

FAB

据我所知,您的代码有效……如果我理解您的要求,那只是扩大范围的问题。请参阅对代码所做的仅有 2 处更改的注释:

Sub mac()
Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column + 1).End(xlUp)) 'Add another column to your selection here
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount, 2) = sValue 'Resize to 2 columns instead of the default 1.

End Sub

PS:如果我误解了您的查询,请告诉我。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章