如何设置一个单元格的价值取决于specefic单元格值

我试图通过检查特定的单元格的值,并设置多个列的值来自动执行Excel表格。

例如,如果A1单元格是“2”,那么我想从B2:D54所有单元格的值等于0.我写了一个代码,但它看起来是错误的。

 Private Sub Worksheet_Change(ByVal Target As Range) //this selects the cell C3 and checks if the value if is 0619 If Range("C3")="0619" Dim example As Range Set example =Range("E3:AE53") example.Value = 0 End if End Sub 

编辑 – 添加Then ,但仍然无法正常工作。

 Private Sub Worksheet_Change(ByVal Target As Range) //this selects the cell C3 and checks if the value if is 0619 If Range("C3")="0619" Then Dim example As Range Set example =Range("E3:AE53") example.Value = 0 End if End Sub 

  • 你错过了Then在与If

  • VBA中的注释是以' ,not //开头' ,所以这不会正确parsing。

  • If Range("C3")="0619"请记住,Excel将从数字中删除前导零。 如果您将格式化为文本值,只有前导零。

  • 编辑: If Range("C3").ValueIf Range("C3")更好


 Private Sub Worksheet_Change(ByVal Target As Range) 'this selects the cell C3 and checks if the value if is 0619 If Range("C3").Value = "0619" Then Dim example As Range Set example = Range("E3:AE53") example.Value = 0 End If ' Range("A1").Select End Sub 
  • 只有在C3改变时才执行工作。
  • 如果C3是格式为0000(前导零)的数字,则使用If Range("C3").Text ="0619" Then
  • 如注释中所述,禁用事件或者当您更改单元格中的值时,您的例程将尝试在其本身之上运行。
  • 事件驱动的子程序应该有错误控制

码:

 Private Sub Worksheet_Change(ByVal Target As Range) if not intersect(target, range("C3")) is nothing then on error goto safe_exit application.enableevents = false select case range("C3").text case "0619" Range("E3:AE53") = 0 case else 'do nothing end select End if safe_exit: application.enableevents = true End Sub 

我已将您的标准检查更改为Select Case语句,以便更容易地适应其他条件。