如何设置一个单元格的价值取决于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").Value
比If 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语句,以便更容易地适应其他条件。
- Excel专用列提取
- 消除重复并列出单个单元格中的第二列
- 如何在Excel中格式化date列
- 将Excel数据转换为具有固定列位置的文本文件
- INDEX(INDIRECT(“DefinedName”),1)=#REF,而INDEX(DefinedName,1)工作
- Excel工作表join而不覆盖列
- Excel VBA使用正则expression式查找和屏蔽PAN数据,以实现PCI DSS合规性
- 如何将joomla用户和用户configuration文件转储为正确的excel
- C# – Microsoft.Office.Interop.Excel.Sheets到Microsoft.Office.Interop.Excel.Worksheet