仅在已设置时包含 range.address 的公式

Formula to include range.address only if it has been set

我正在使用宏将公式写入 Excel 工作表的单元格中。使用以下代码将公式写入单元格,其中 xWF1 到 wWF5 均为单单元格范围。

xWF1.Formula = "=" & xWF2.Address(True,True) & "-" & xWF3.Address(True,True) & "-" & xWF4.Address(True,True) & "-" & xWF5.Address(True,True)

xWF2 到 xWF5 如果存在,则在代码中较早设置。当其中之一不存在时,上面的代码行会出错。

我想要的是编写公式的代码仅包含那些存在的范围。例如,如果 xWF4 不存在,则公式为 xWF2-xWF3-xWF5

编写此代码的更好方法是什么?

我认为如果你遵循@Ron_Rosenfeld 的建议和陷阱来了解各种可能性,这个应该对你有用。

我不检查 xWF1

Public Sub TestMacro()

    Dim strxWF2     As String
    Dim strxWF3     As String
    Dim strxWF4     As String
    Dim strxWF5     As String
    
    Dim strFormula  As String
    
    If Not (xWF2 Is Nothing) Then strxWF2 = xWF2.Address(True, True)
    If Not (xWF3 Is Nothing) Then strxWF3 = xWF3.Address(True, True)
    If Not (xWF4 Is Nothing) Then strxWF4 = xWF4.Address(True, True)
    If Not (xWF5 Is Nothing) Then strxWF5 = xWF5.Address(True, True)
    
    If (strxWF2 <> "") Or (strxWF3 <> "") Or (strxWF4 <> "") Or (strxWF5 <> "") Then
        
        strFormula = "="
        If (strxWF2 <> "") Then strFormula = strFormula & strxWF2
        If (strxWF3 <> "") Then strFormula = strFormula & "-" & strxWF3
        If (strxWF4 <> "") Then strFormula = strFormula & "-" & strxWF4
        If (strxWF5 <> "") Then strFormula = strFormula & "-" & strxWF5
    
        xWF1.Formula = strFormula
    End If
    
End Sub

Nothing

的测试范围
Option Explicit

Sub Test()
    
    Dim xWF1 As Range, xWf2 As Range, xWf3 As Range, xWf4 As Range, xWf5 As Range
        
    Set xWF1 = Range("A1")
    'Set xWf2 = Range("A2")
    'Set xWf3 = Range("A3")
    'Set xWf4 = Range("A4")
    'Set xWf5 = Range("A5")
    
    ' The above is irrelevant for your code.
    
    Dim rArr As Variant: rArr = Array(xWf2, xWf3, xWf4, xWf5)
    Dim dFormula As String: dFormula = "="
    
    Dim rg As Variant
    
    For Each rg In rArr
        If Not rg Is Nothing Then dFormula = dFormula & rg.Address & "-"
    Next rg
    ' Remove the trailing '-', or the '=' if all four ranges are 'Nothing'.
    dFormula = Left(dFormula, Len(dFormula) - 1)
    
    xWF1.Formula = dFormula

End Sub