2016-11-21 37 views
0

所以我有多个宏的输入值的工作簿中的单元格。这是我遇到的麻烦的相关部分:有什么方法可以检查我添加到单元格的值是否已经在单元格中?

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)最终看起来像“= cell(wregrow,wregcol)+ cell(wregrow,wregcol)”。如何检查单元格是否已在R1C1公式中引用,以便我可以避免再次添加该值?

+0

第一:请不要使用“'+'”作为文本(“'&'”更好的原因有几个)。要运行检查,只需使用'instr()'来检查是否'WREG'!R“&CStr(wregrow)&”C“&CStr(wregcol)'是Cells(cshrow,cshcol)的一部分。 FormulaR1C1';) –

+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 
相关问题