Dyanmic VBA代码,用于在表名更改时更改vba

我有一个VBA代码,指定特定的工作表名称,例如工作表2,

但是,如果有人忘记将工作表名称更改为sheet2,我可以添加一段dynamic代码来自动更改调用工作表名称的vba代码吗? 例如从左边开始的第二张纸。

代码模块1:

Sub Calculation() Range("P2:P800").Select Application.CutCopyMode = False Selection.ClearContents Dim dict1 As Object Dim c1 As Variant, k As Variant Dim currWS As Worksheet Dim i As Double, lastRow As Double, tot As Double Dim number1 As Double, number2 As Double, firstRow As Double Set dict1 = CreateObject("Scripting.Dictionary") Set currWS = ThisWorkbook.Sheets("Trade data") 'get last row withh data in Column A lastRow = currWS.Cells(Rows.Count, "M").End(xlUp).Row 'put unique numbers in Column A in dict1 c1 = Range("M2:V" & lastRow) For i = 1 To UBound(c1, 1) If c1(i, 1) <> "" Then 'make combination with first 4 characters dict1(Left(c1(i, 1), 4) & "," & Left(c1(i, 8), 4) & "," & Left(c1(i, 6), 10) & "," & Left(c1(i, 10), 7)) = 1 End If Next i 'loop through all the numbers in column A For Each k In dict1.keys number1 = Split(k, ",")(0) number2 = Split(k, ",")(1) tot = 0 firstRow = 0 For i = 2 To lastRow If k = Left(currWS.Range("M" & i).Value, 4) & "," & Left(currWS.Range("T" & i).Value, 4) & "," & currWS.Range("R" & i).Value & "," & (currWS.Range("O" & i).Value) Then If firstRow = 0 Then firstRow = i End If tot = tot + currWS.Range("W" & i).Value End If Next i currWS.Range("P" & firstRow) = tot Next k Call Consolidate Call SingleTradeMove End Sub 

模块2代码:Sub SingleTradeMove()

  Dim wsTD As Worksheet Set wsTD = Worksheets("Trade data") Sheets("UnMatching").Range("A2:AK600").ClearContents With wsTD lastRow = .Range("A" & .Rows.Count).End(xlUp).Row For i = 2 To lastRow If Left(.Cells(i, "M"), 4) <> Left(.Cells(i, "T"), 4) _ Or .Cells(i, "O") <> .Cells(i, "V") _ Or .Cells(i, "R") <> .Cells(i, "Y") Then .Cells(i, "J").EntireRow.Copy _ Destination:=Sheets("UnMatching").Range("A" & Rows.Count).End(xlUp).Offset(1) End If Next i End With End Sub 

假设您有一张名为“工作数据”的工作表,并将其编程为Sheets("Work data") 。 为了使其dynamic化,可以在启动Visual Basic编辑器时在括号之前使用该名称。

Visual Basic编辑器截图

例如,你有这样的代码:

 Sheets("Work data").Select 

现在你可以改变这个:

 Sheet1.Select 

这样,无论用户如何更改表单名称,它都将始终有效。 但请记住,Sheet1也可以改变,但只能在Visual Basic编辑器属性中完成。 你可以用密码来保护VBA,所以没有人可以意外地改变它。