一位善良的绅士在此之前帮助我生成一些VBA代码以在excel中创建占位符文本。现在我不熟悉这样的代码,我不确定如何实现我正在寻找的结果。我想知道我是否能得到一些帮助。
使用他的代码,我能够达到我想要的效果,但是我现在需要为另一个具有不同默认文本的列放置另一个占位符。
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
我尝试使用此代码在备用单元格中创建相同的结果,但我不认为这是正确的方法。如果有人能够朝着正确的方向推动我,我将永远感激不尽。
这是我想出的;
'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
答案 0 :(得分:1)
这是怎么回事:
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
' i.e. 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
由于您的默认值位于“更改范围”列LEFT的第1行,因此您基本上只需切换defaultFormula
即可查看。我使用R1C1样式表示法。通过这种方式,它会查看您的Target.Colum
,即您更改单元格的列,然后查看左列一列(- 1
),最多行一行(R1
表示“行1” )。
我也改变了If Intersect() Is Nothing Then Exit Sub
只是为了个人偏好,但你当然可以离开你的。