2016-11-21 69 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 
相關問題