动态更改工作表更改事件代码

时间:2019-07-01 09:00:02

标签: excel vba

我制作了一个源工作簿,从中导入了工作表作为模板。在模板中,我在工作表更改事件中有一些代码。此代码使用工作表的名称。当我导入模板时,我也更改了名称。我想用新的工作表名称更新模板。这必须通过代码自动发生。

这是事件代码;

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r1, r2, r3, trh, myMultipleRange As Range
Set r1 = ThisWorkbook.Sheets("DATA").Range("C:C")
Set r2 = ThisWorkbook.Sheets("DATA").Range("E:E")
Set r3 = ThisWorkbook.Sheets("DATA").Range("G:G,H:H")
Set trh = ThisWorkbook.Sheets("DATA").Range("V:V")
Set myMultipleRange = Union(r1, r2, r3)

If Not Intersect(Target, myMultipleRange) Is Nothing Then
lastrow = ThisWorkbook.Sheets("DATA").Cells(Rows.count, 2).End(xlUp).Row
For xsay = 2 To lastrow
    Cells(xsay, "F") = Cells(xsay, "C") * Cells(xsay, "E")
    Cells(xsay, "I") = Cells(xsay, "F") * Cells(xsay, "G")
    Cells(xsay, "J") = Cells(xsay, "F") - Cells(xsay, "I")
    Cells(xsay, "K") = Cells(xsay, "J") * Cells(xsay, "H")
    Cells(xsay, "L") = Cells(xsay, "J") + Cells(xsay, "K")

    If Cells(xsay, "AA") = "STG" Then
        Range("E" & xsay & ":F" & xsay).NumberFormat = "[$£-809]#,##0.00"
        Range("I" & xsay & ":M" & xsay).NumberFormat = "[$£-809]#,##0.00"
    ElseIf Cells(xsay, "AA") = "DOLAR" Then
        Range("E" & xsay & ":F" & xsay).NumberFormat = "[$$-409]#,##0.00"
        Range("I" & xsay & ":M" & xsay).NumberFormat = "[$$-409]#,##0.00"
    ElseIf Cells(xsay, "AA") = "EURO" Then
        Range("E" & xsay & ":F" & xsay).NumberFormat = "[$€-2] #,##0.00"
        Range("I" & xsay & ":M" & xsay).NumberFormat = "[$€-2] #,##0.00"
    End If

    If Cells(xsay, "Z") <> 0 Then
        Var = xsay + (Cells(xsay, "Z") - 1)
        Cells(xsay, "M").Formula = "=SUM(L" & xsay & ":L" & Var & ")"
    End If

    Next xsay
End If

End Sub

这是导入代码;

Sub yeni_sayfa_ekle()

Dim WB As Workbook
Dim SourceWB As Workbook
Dim WS As Worksheet
Dim ASheet As Worksheet

'Turns off screenupdating and events:
Application.ScreenUpdating = False
Application.EnableEvents = False

'Sets the variables:
Set WB = ActiveWorkbook
Set ASheet = ActiveSheet
Set SourceWB = Workbooks.Open(WB.Path & "\source.xlsm")  'Modify to match

'Copies each sheet of the SourceWB to the end of original wb:
For Each WS In SourceWB.Worksheets
If WS.Name = "DATA" Then
WS.Copy after:=WB.Sheets(WB.Sheets.Count)
ism = usrSiparis.cmbFirm.Value
WB.Sheets("DATA").Name = ism
WB.Sheets(ism).Visible = xlSheetHidden
End If
Next WS

SourceWB.Close savechanges:=False
Set WS = Nothing
Set SourceWB = Nothing

WB.Activate
ASheet.Select
Set ASheet = Nothing
Set WB = Nothing

Application.EnableEvents = True

End Sub

0 个答案:

没有答案