在VBA中使用ListObject列名称

工作表变更时,我需要执行一些VBA代码。 为此我有一个If-Then-else的情况。

在任何特定的行(我有可变数量的行(即行项目)):

if column "Type" = Range("A") then column "Amount" needs to be unlocked set to the value of Range("B") and locked else if column "Type" = Range("C") then column "Amount" needs to be unlocked set to the value of Range("C") and locked else the column "Amount" needs to unlocked. 

在工作表更改事件中,我使用ActiveSheet.Protect解锁/locking,并使用范围内的密码进行解锁。

我现在试图找出如何做到这一点。 具体来说,我如何使用列名 – 像公式的?

=== Excel 2007+ ===

如果您使用Excel 2007+,我推荐使用ListObject,ListColumns和ListRows(研究对象模型)。

我的方法背后的哲学:

  1. 表格,数据和报告应该总是分开的,所以…

  2. 收集所有的数据到一个表格,在一个专门的工作表。 select你的数据和Ctrl +(T或L)。 确保每张纸只有一个数据表。

  3. 使用表格,您将能够使用ListObject,ListColumns和ListRows对象。

这是整个事情的完成代码。

 Public Sub test() IntersectColumnRows ActiveSheet, "", "Type", "Amount", Range("A1"), Range("B1"), Range("C1") End Sub Public Sub IntersectColumnRows(currentSheet As Worksheet, sheetPassword As String, columnTitle_Type As String, columnTitle_Amount As String, rangeA As Range, rangeB As Range, rangeC As Range) 'variable declaration Dim listO As ListObject Set listO = currentSheet.ListObjects(1) 'Takes care of sheet protection Dim isSheetProtected As Boolean isSheetProtected = currentSheet.ProtectionMode If isSheetProtected Then _ currentSheet.Unprotect (sheetPassword) 'store your type column Dim columnRangeType As Range Set columnRangeType = listO.ListColumns(columnTitle_Type).Range 'store your 2nd column Dim columnRangeAmount As Range Set columnRangeAmount = listO.ListColumns(columnTitle_Amount).Range 'the actual routine you are asking for Dim listR As ListRow For Each listR In listO.ListRows 'intersect the TYPE column with the current row Dim typeRangeIntersection As Range Set typeRangeIntersection = Application.Intersect(listR.Range, columnRangeType) 'intersect the AMOUNT column with the current row Dim amountRangeIntersection As Range Set amountRangeIntersection = Application.Intersect(listR.Range, columnRangeAmount) 'the logic you required If typeRangeIntersection.Value = rangeA.Value Then amountRangeIntersection.Locked = False amountRangeIntersection.Value = rangeB.Value amountRangeIntersection.Locked = True ElseIf typeRangeIntersection.Value = rangeC.Value Then amountRangeIntersection.Locked = False amountRangeIntersection.Value = rangeC.Value amountRangeIntersection.Locked = True Else amountRangeIntersection.Locked = False End If Next 'Cleans up sheet protection If isSheetProtected Then _ currentSheet.Protect (sheetPassword) End Sub 

这是“我怎么做”:

  1. 存储所有必需列的ListColumn.Range(types,金额)

  2. For循环与每个ListRow …

  3. 我将ListRow.Range与ListColumn.Range相交

  4. 应用您所需的逻辑

除了代码,研究如何…

  1. 我在其中包含了PROTECT / PASSWORD逻辑,所以如果你愿意,可以把它删除。

  2. 每个variables都有一个非常明确的名字

  3. 我没有包含任何硬编码的值,所以它仍然是参数化的,如果你需要适应不同的表格