[英]Formula if cell = value to carry out formula else…Excel VBA
我試圖修改下面的代碼以檢查字符串---
。 如果字符串存在,則返回值9999,否則執行公式:
.Formula = "=IF(" & strLowLimCol & "2" = ""---"," & _ strMeasCol & "2-" & strLowLimCol & "2," & _ 9999)"
你能告訴我我的錯誤在哪里嗎?
這是完整的代碼:
Option Explicit
Sub ReturnMarginal()
Dim ws As Worksheet
Dim lngLowLimCol As Long, strLowLimCol As String
Dim lngHiLimCol As Long, strHiLimCol As String
Dim lngMeasCol As Long, strMeasCol As String
Dim lngLastRow As Long
Dim wsf As WorksheetFunction
' get worksheetfunction references
Set wsf = Application.WorksheetFunction
' iterate worksheets
For Each ws In ThisWorkbook.Worksheets
' validate LowLimit label is on sheet
If Not (ws.Rows(1).Find("LowLimit") Is Nothing) Then
' get location of input data columns and number of rows
lngLowLimCol = wsf.Match("LowLimit", ws.Rows(1), 0)
lngHiLimCol = wsf.Match("HighLimit", ws.Rows(1), 0)
lngMeasCol = wsf.Match("MeasValue", ws.Rows(1), 0)
lngLastRow = ws.Cells(1, lngLowLimCol).End(xlDown).Row
' get column letters for input data columns
strLowLimCol = Split(ws.Cells(1, lngLowLimCol).Address(True, False), "$")(0)
strHiLimCol = Split(ws.Cells(1, lngHiLimCol).Address(True, False), "$")(0)
strMeasCol = Split(ws.Cells(1, lngMeasCol).Address(True, False), "$")(0)
' output headers
ws.Range("P1") = "Meas-LO"
ws.Range("Q1") = "Meas-Hi"
ws.Range("R1") = "Min Value"
ws.Range("S1") = "Marginal"
' assign formulas to outputs
' Meas-LO
'Range("P2:P" & lngLastRow).Select
' With Selection
' Selection.NumberFormat = "General"
' .Value = .Value
' End With
With ws.Range("P2:P" & lngLastRow)
.Formula = "=IF(" & strLowLimCol & "2" = ""---"," &
strMeasCol & "2-" & strLowLimCol & "2," & _
9999)"
End With
' Meas-Hi
With ws.Range("Q2:Q" & lngLastRow)
.Formula = "=IF(ISNUMBER(" & strHiLimCol & "2)," & _
strMeasCol & "2-" & strHiLimCol & "2," & _
9999 & "2)"
'strMeasCol & "2)"
End With
' Min Value
With ws.Range("R2:R" & lngLastRow)
.Formula = "=MIN(P2,Q2)"
End With
' Marginal
With ws.Range("S2:S" & lngLastRow)
.Formula = "=IF(AND(R2>=-3,R2<=3),""Marginal"",R2)"
End With
End If
Next ws
End Sub
您有幾個錯誤的“”,我認為您的行應為:
.Formula = "=IF(" & strLowLimCol & "2 = ""---""," & _
strMeasCol & "2-" & strLowLimCol & "2, 9999)"
因此最終輸出將是(如果strLowLimCol為“ B”而strMeasCol為“ C”)
IF(B2 =“ ---”,C2-B2,9999)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.