在标题中searchWord并在Excel VBA中设置要用于计算的列

我正在尝试在Excel电子表格的列上执行计算。 列名是:LowLimit,HighLimit和MeasValue“我现在只能用'硬编码'列号来进行计算(如下面的代码所示)。如果列位置保持不变但是,列的位置在整个工作簿中是变化的,但是它们总是按照相同的顺序,例如,在表1中,标题LowLimit,HighLimit和MeasValue分别位于J,K,L位置。他们将分别改变位置到G,H,I。

如何search标题的位置,然后在计算中使用它,而不是像下面这样做硬编码?

这是我迄今为止(代码由蒂姆·威廉斯编辑):

Sub SearchFolders() 'UpdatebySUPERtoolsforExcel2016 Dim xOut As Worksheet Dim xWb As Workbook Dim xWks As Worksheet Dim InterSectRange As Range Dim lowLimCol As Integer Dim hiLimCol As Integer Dim measCol As Integer Application.ScreenUpdating = False Set xWb = ActiveWorkbook For Each xWks In xWb.Sheets xRow = 1 With xWks .Cells(xRow, 16) = "Meas-LO" .Cells(xRow, 17) = "Meas-Hi" .Cells(xRow, 18) = "Min Value" .Cells(xRow, 19) = "Marginal" LastRow = .UsedRange.Rows.Count lowLimCol = Application.WorksheetFunction.Match("LowLimit", xWks.Range("1:1"), 0) hiLimCol = Application.WorksheetFunction.Match("HighLimit", xWks.Range("1:1"), 0) measLimCol = Application.WorksheetFunction.Match("MeasValue", xWks.Range("1:1"), 0) .Range("P2").Formula = "=L2-J2" .Range("P2").AutoFill Destination:=.Range("P2:P" & LastRow) .Range("Q2").Formula = "=K2-L2" .Range("Q2").AutoFill Destination:=.Range("Q2:Q" & LastRow) .Range("R2").Formula = "=min(P2,Q2)" .Range("R2").AutoFill Destination:=.Range("R2:R" & LastRow) .Range("S2").Formula = "=IF(AND(R2>=-3, R2<=3), ""Marginal"", R2)" .Range("S2").AutoFill Destination:=.Range("S2:S" & LastRow) End With Application.ScreenUpdating = True 'turn it back on Next xWks 

设置三个列标题的整数variables(例如LowLimCol)

find这些与:

lowLimCol = Application.Worksheetfunction.Match("LowLimit", ws.Range("1:1"), 0)

然后可以通过使用cells定义范围来使用这些variables,例如

range("A1:A5")

可以改写为

range(cells(1, LowLimCol).address, cells(5, LowLimCol).address)

编辑:第二部分后评论 –

如果您不需要填充公式,则可以将总和的实际值放在单元格中:

 .Range("P2").Value = .Cells(2, measLimCol).Value - .Cells(2, lowLimCol).Value 

但是,由于您将该公式推广到最后一行,因此可以使用连接在公式string“=”和“ – ”和VBA编码的单元地址之间进行交换,例如:

 .Range("P2").Formula = "=" & Cells(2, measLimCol).Address & "-" & Cells(2, lowLimCol).Address 

这将在单元格“P2”中以“= $ L $ 2- $ J $ 2”的绝对引用forms出现,所以为了能够进行洪泛填充,需要在cells(x,y).address之后指定FALSE来摆脱$$$ cells(x,y).address部分例如cells(x,y).address(false,false)

这意味着该行将是:

 .Range("P2").Formula = "=" & Cells(2, measLimCol).Address(false, false) & "-" & Cells(2, lowLimCol).Address (false, false) 

希望有所帮助! 您也可以一次性填写整个范围,以便两行

 .Range("P2").Formula = "=L2-J2" .Range("P2").AutoFill Destination:=.Range("P2:P" & LastRow) 

可能成为:

 .Range("P2:P" & LastRow).Formula = "=" & Cells(2, measLimCol).Address (False, False) & "-" & Cells(2, lowLimCol).Address (False, False)