run macros dynamically on value change |VBA|Excel|

2019-08-16 06:03发布

I have Sheet 1 and Sheet  

Sheet 1 => https://paste.pics/6d48d50d54592eb1bdcb31e727b44958

Sheet 2 => https://paste.pics/80f4230bf6819a80ed36e1b6415ece08

Value of Sheet 1 => F5 => '50'  => is referenced in Sheet 2  => E4 => '50'

When i enter Value in Sheet 1 in place of F5 => Value gets Change in Sheet 2 => E4 => Automatically

Now the issue is I want to print the DATA 1 and DATA 2 of Sheet 2 => That many times => how much value which is shown in place of Sheet 2 => E4 [Position] => in place of COLUMN => 'I' and 'J'

Like this Below Output :https://paste.pics/494c856d2908a83ca031ee20bb706a09

My code which partially print only one Column output but need to PRINT 'RAM' and 'RAJ' => COLUMN => 'I' and 'J'

Module : 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).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

Sheet 1 code :

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

标签: excel vba
1条回答
smile是对你的礼貌
2楼-- · 2019-08-16 06:26

If print means just filling the cells, then you can use following sub. Modify the code to adjust it with Worksheet_Change event

Sub FillNames()
Dim ws As Worksheet
Dim i, destLen As Long

Set ws = Worksheets("Sheet2")
destLen = ws.Range("E4")

    For i = 1 To destLen
        ws.Cells(i + 1, "I") = ws.Range("E8")
        ws.Cells(i + 1, "J") = ws.Range("E12")
    Next

Set ws = Nothing
End Sub
查看更多
登录 后发表回答