根据 excel 中的下拉列表自动填充单元格
Autofill cells based on drop down list in excel
我正在尝试创建一个 VBA,它根据表单中的下拉列表为我提供自动值。问题是,当我 运行 宏时,它会导致错误并且 excel 停止工作。在这种情况下,我们非常欢迎任何帮助。
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("$G") = "UD Sheet" Then
Rows("20:25").EntireRow.Hidden = False
Else
Rows("21:25").EntireRow.Hidden = True
End If
If Range("G12").Value = "Flex Tape" Then
Range("B20").Value = "None"
Else
Range("B20").Value = ""
End If
exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub
首先,在您的代码中,无需在 End Sub 之前放置 Exit Sub。
代码将在该行之后结束,因此这是一种冗余。
接下来您需要了解的是,如果您不明确禁用更改事件,它将继续触发它。因此,这意味着当您在 Sheet 上隐藏一行时,更改事件将继续发生,因为 Sheet 上会发生更改。即(隐藏行)。
为此,您需要使用 Application.EnableEvents = False 禁用应用程序的 EventsListeners。因此应用程序可以根据第一个事件做一件事情。
接下来您需要记住的是跟踪更改发生的位置并启动您的程序。 Target 是一个范围对象,它将 return 发生特定变化的范围 Sheet。
为此,您需要验证是否需要使用 Intersect 函数根据目标触发例程。
整个代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Not Intersect(Target, Range("G11")) Is Nothing Then
If Range("$G") = "UD Sheet" Then
Rows("20:25").EntireRow.Hidden = False
Else
Rows("21:25").EntireRow.Hidden = True
End If
End If
If Not Intersect(Target, Range("G12")) Is Nothing Then
If Range("G12").Value = "Flex Tape" Then
Range("B20").Value = "None"
Else
Range("B20").Value = ""
End If
End If
Application.EnableEvents = True
End Sub
我正在尝试创建一个 VBA,它根据表单中的下拉列表为我提供自动值。问题是,当我 运行 宏时,它会导致错误并且 excel 停止工作。在这种情况下,我们非常欢迎任何帮助。
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("$G") = "UD Sheet" Then
Rows("20:25").EntireRow.Hidden = False
Else
Rows("21:25").EntireRow.Hidden = True
End If
If Range("G12").Value = "Flex Tape" Then
Range("B20").Value = "None"
Else
Range("B20").Value = ""
End If
exitHandler:
Application.EnableEvents = True
Exit Sub
End Sub
首先,在您的代码中,无需在 End Sub 之前放置 Exit Sub。 代码将在该行之后结束,因此这是一种冗余。
接下来您需要了解的是,如果您不明确禁用更改事件,它将继续触发它。因此,这意味着当您在 Sheet 上隐藏一行时,更改事件将继续发生,因为 Sheet 上会发生更改。即(隐藏行)。
为此,您需要使用 Application.EnableEvents = False 禁用应用程序的 EventsListeners。因此应用程序可以根据第一个事件做一件事情。
接下来您需要记住的是跟踪更改发生的位置并启动您的程序。 Target 是一个范围对象,它将 return 发生特定变化的范围 Sheet。
为此,您需要验证是否需要使用 Intersect 函数根据目标触发例程。
整个代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Not Intersect(Target, Range("G11")) Is Nothing Then
If Range("$G") = "UD Sheet" Then
Rows("20:25").EntireRow.Hidden = False
Else
Rows("21:25").EntireRow.Hidden = True
End If
End If
If Not Intersect(Target, Range("G12")) Is Nothing Then
If Range("G12").Value = "Flex Tape" Then
Range("B20").Value = "None"
Else
Range("B20").Value = ""
End If
End If
Application.EnableEvents = True
End Sub