我有一个VBA脚本,这样当单元格值为'N / A'时,它会向右偏移一个单元格并写入'N / A'。该脚本有效,但它会导致Excel停止响应。我希望每次对单元格范围进行更改时都这样做,所以我将其设为“Worksheet_Change”。我的想法(我可能也可能是错误的)是它必须对表格的每次更改都要这样做,导致程序“烧坏”。
BWLinkNames[key]
答案 0 :(得分:0)
If you must use VBA for this, you can try this. Disable events in your loop when changes are being made to be sure you are not getting stuck in a infinite loop. Also, if your range is dynamic I highly recommend replacing your lower bound (E1000) with a dynamic variable that tracks the last row in your data set to minimize the number of loops your macro runs.
For instance, if your macro is on a sheet, you can use this as the lower bound in your range, which would then be set rng=Range("E267:E" & LROW)
Dim LROW as Long
LROW = Range("E" & Rows.Count).End(xlUp).Row
Macro
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Dim i As Long
Set rng = Range("E267:E1000")
For Each cell In rng
Application.Enable Events = False
'test if cell is empty
If cell.Value = "N/A" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "N/A"
End If
Application.EnableEvents=True
Next
End Sub
答案 1 :(得分:0)
If you are physically changing a cell, you can target the range of cells being changed. For example, the below code kicks in every time you physically change a cell in the specified range.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub ' this stops code error if more than one cell is changed at once
If Not Application.Intersect(Target, Me.Range("E267:E1000")) Is Nothing Then ' indicates the Target range
If Target.Value = "N/A" Then
Target.Offset(, 1) = Target.Value
End If
End If
End Sub