有没有办法检查我添加到单元格中的值是否已经在单元格中?

时间:2016-11-21 19:51:43

标签: excel vba excel-vba

所以我有多个宏,它们将值输入到工作簿中的单元格中。这是我遇到问题的相关部分:

If wsCsh.Cells(cshrow, cshcol) = "" Then
      Cells(cshrow, cshcol - 1).FormulaR1C1 = "='WREG'!R" + CStr(wregrow) + "C" + CStr(wregcol)
Else
      Cells(cshrow, cshcol - 1).FormulaR1C1 = Cells(cshrow, cshcol).FormulaR1C1 + "+'WREG'!R" + CStr(wregrow) + "C" + CStr(wregcol)
End If

如果单元格(cshrow,cshcol)为空,则输入R1C1公式将其链接到单元格(wregrow,wregcol),如果不是,则将单元格(wregrow,wregcol)添加到任何单元格中是在牢房里。但是,假设我连续两次运行此宏。然后它基本上将细胞(wregrow,wregcol)添加到细胞两次,因此细胞(cshrow,cshcol)最终看起来像" =细胞(wregrow,wregcol)+细胞(wregrow,wregcol)"。如何检查R1C1公式中是否已引用单元格,以便我可以避免再次添加该值?

1 个答案:

答案 0 :(得分:0)

Dim extraBit As String

With wsCsh
    extraBit = "+'WREG'!R" & wregrow & "C" & wregcol
    If .Cells(cshrow, cshcol).Value = "" Then
        'Set the formula to the "extra bit"
        .Cells(cshrow, cshcol - 1).FormulaR1C1 = "=" & extraBit
    ElseIf Right(Cells(cshrow, cshcol - 1).FormulaR1C1, Len(extraBit)) <> extraBit Then
        'Add the "extra bit" if the current formula doesn't already end with it
        .Cells(cshrow, cshcol - 1).FormulaR1C1 = .Cells(cshrow, cshcol).FormulaR1C1 & extraBit
    End If
End With