我是VBA的新手,想要使用带有对不同单元格值的引用的case语句(在同一个文件中)。
目前我使用下面的If语句进行此操作。有人可以告诉我如何在这里使用Case,以便我不必总是检查所有单个If语句吗?
到目前为止我的代码:
'case 1
If Me.selCategory = Worksheets("Admin").Range("B2") Then
Me.txtRestNote = Worksheets("Admin").Range("F2")
Me.txtCustEmail = Worksheets("Admin").Range("A26")
End If
'case 2
If Me.selCategory = Worksheets("Admin").Range("B3") Then
Me.txtRestNote = Worksheets("Admin").Range("F3")
Me.txtCustEmail = Worksheets("Admin").Range("A27")
End If
'case 3
If Me.selCategory = Worksheets("Admin").Range("B4") Then
Me.txtRestNote = Worksheets("Admin").Range("F4")
Me.txtCustEmail = Worksheets("Admin").Range("A28")
End If
'case 4
If Me.selCategory = Worksheets("Admin").Range("C2") Then
Me.txtRestNote = Worksheets("Admin").Range("G2")
Me.txtCustEmail = Worksheets("Admin").Range("A29")
End If
'case 5
If Me.selCategory = Worksheets("Admin").Range("C3") Then
Me.txtRestNote = Worksheets("Admin").Range("G3")
Me.txtCustEmail = Worksheets("Admin").Range("A30")
End If
非常感谢提供任何帮助,蒂姆。
答案 0 :(得分:3)
试试这个:
With Worksheets("Admin")
Select Case Me.selCategory
Case .Range("B2")
Me.txtRestNote = .Range("F2")
Me.txtCustEmail = .Range("A26")
Case .Range("B3")
Me.txtRestNote = .Range("F3")
Me.txtCustEmail = .Range("A27")
Case .Range("B4")
Me.txtRestNote = .Range("F4")
Me.txtCustEmail = .Range("A28")
Case .Range("C2")
Me.txtRestNote = .Range("G2")
Me.txtCustEmail = .Range("A29")
Case .Range("C3")
Me.txtRestNote = .Range("G3")
Me.txtCustEmail = .Range("A30")
End Select
End With