如果find第一行的特定单词,如果找不到,则在Excel VBA中转到下一页

我试图实现一些VBA代码,如果在第一行中,“LowLimit”的话。 如果find,则执行计算并移至下一页。 如果找不到,则转到下一张表。

我已经声明了“LowLimit”, Dim lowLimHdr As String 。 在进入我的计算之前,如何使用这个参数来实现IF...THEN

这是我迄今为止:

 Sub ReturnMarginal() '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 Dim lowLimHdr As String Application.ScreenUpdating = False Set xWb = ActiveWorkbook For Each xWks In xWb.Sheets xRow = 1 With xWks FindString = "LowLimit" 'If .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:P" & LastRow).Formula = "=" & Cells(2, measLimCol).Address(False, False) & "-" & Cells(2, lowLimCol).Address(False, False) .Range("Q2:Q" & LastRow).Formula = "=" & Cells(2, hiLimCol).Address(False, False) & "-" & Cells(2, measLimCol).Address(False, False) .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 End Sub 

 If Not xWks.Rows(1).Find(FindString) Is Nothing Then ' do your calculations End If 

您需要将variableslowLimColHighLimColmeasColVariant s,因为在不匹配的情况下, Application.Match返回一个错误variables,否则返回表示find的列的索引的数字。

 Dim lowLimCol. hiLimCol, measCol lowLimCol = Application.Match("LowLimit", xWks.Range("1:1"), 0) hiLimCol = Application.Match("HighLimit", xWks.Range("1:1"), 0) measLimCol = Application.Match("MeasValue", xWks.Range("1:1"), 0) ' Check if all these columns were found in the header to proceed: If Not (IsError(lowLimCol) Or IsError(highLimCol) Or IsError(measLimCol)) Then ' ' You calculations here ' End If 

ps的variableslowLimHdr是你的代码似乎不必要的。

你也可以保持它们声明为整数然后使用

 If Application.WorksheetFunction.CountIf(Range("1:1"), LowLimHdr) > 0 Then ' do all my calcuations in here End If 

这是假设任何表“LowLimit”肯定会有其他头,否则以前的答案是更好的错误捕捉。

编辑:在与ASH的答案类似的静脉,要做全错误捕捉的情况下,任何标题丢失,你需要三重检查:

 If Application.WorksheetFunction.CountIf(Range("1:1"), "LowLimit") > 0 And _ Application.WorksheetFunction.CountIf(Range("1:1"), "HighLimit") > 0 And _ Application.WorksheetFunction.CountIf(Range("1:1"), "MeasValue") > 0 Then ' do all my calcuations in here End If