占位符文本Excel – 多个默认值

一位仁慈的先生帮助我在这里生成一些VBA代码,在excel中创build占位符文本。 现在我不熟悉这样的代码,我不知道如何实现我期待的结果。 我想知道我是否可以得到一点帮助。

用他的代码在这里,我能够达到我正在寻找的效果,但是现在我需要为另一个不同的默认文本列设置另一个占位符。

Private Sub Worksheet_Change(ByVal Target As Range) 'the formula reference Dim defaultFormula As String defaultFormula = "=$C$1" 'The default text cell: Dim defaultText As Range Set defaultText = Range("C1") 'The cells you want to monitor: Dim rng As Range Set rng = Range("C7:C999,D7:D999,G7:G999") '## Modify as needed 'Cell iterator Dim cl As Range If Intersect(Target, rng) Is Nothing Then Exit Sub 'Avoid infinite looping Application.EnableEvents = False 'If the user has deleted the value in the cell, then replace it with the formula: For Each cl In Intersect(Target, rng) If Trim(cl.Value) = vbNullString Then cl.Formula = defaultFormula End If Next 'Turn on Events: Application.EnableEvents = True End Sub 

我试图用这个代码在这里创build一个替代单元格的相同的结果,但我不认为这是正确的方法。 如果有人能把我推向正确的方向,我将永远感激。

这就是我想出来的。

 'the formula reference Dim defaultFormula1 As String defaultFormula1 = "=$D$1" 'The default text cell: Dim defaultText1 As Range Set defaultText1 = Range("D1") 'The cells you want to monitor: Dim rng1 As Range Set rng1 = Range("E7:E999") '## Modify as needed 'Cell iterator Dim dl As Range If Intersect(Target, rng1) Is Nothing Then Exit Sub 'Avoid infinite looping Application.EnableEvents = False 'If the user has deleted the value in the cell, then replace it with the formula: For Each dl In Intersect(Target, rng1) If Trim(dl.Value) = vbNullString Then dl.Formula = defaultFormula1 End If Next 'Turn on Events: Application.EnableEvents = True 

这个怎么样:

 Private Sub Worksheet_Change(ByVal Target As Range) ' I am assuming that the Ranges you want to fill with Default Values are ONE column to the RIGHT of the Default Text ' ie Range `D7:D999` will look for the default value in `C1` 'the formula reference Dim defaultFormula As String defaultFormula = "=r1c" & Target.Column - 1 'The default text cell: Dim defaultText As Range Set defaultText = Range("C1") 'The cells you want to monitor: Dim rng As Range Set rng = Range("C7:C999,D7:D999,E7:E999,G7:G999") '## Modify as needed 'Cell iterator Dim cl As Range If Not Intersect(Target, rng) Is Nothing Then 'If the change happened in any of the `rng` ranges 'Avoid infinite looping Application.EnableEvents = False 'If the user has deleted the value in the cell, then replace it with the formula: For Each cl In Intersect(Target, rng) Debug.print cl.value If Trim(cl.Value) = vbNullString Then cl.Formula = defaultFormula End If Next End If 'Turn on Events: Application.EnableEvents = True End Sub 

由于您的默认值位于“更改范围”列的第1行,所以您基本上需要做的就是将您的默认值切换到此处。 我使用R1C1风格的表示法。 这样,它看着你的Target.Colum ,就是你改变一个单元格的列,然后看一列( - 1 ),直到第1行( R1 “第1行”)。

我也改变了If Intersect() Is Nothing Then Exit Sub只是为了个人喜好,但你当然可以离开你的。