EXCEL VBA WorksheetFunction.CountIf()在一个SELECT CASE中

我知道有可能使用If语句,但出于好奇,正如标题中提到的那样,是否可以使用SELECT语句做如下的BOLDED ? 为了更好的理解,我已经提交了我的整个Sub

Sub addNewCust_Click()

 Dim response As String response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2) Select Case response Case False Exit Sub 'Check if response is not an empty value AND record found in "CustomerList" 

(“CustomerList”)。范围(“B:B”),响应)> 0

  MsgBox "'" & response & "' already exists on this sheet." Call addNewCust_Click 'Check if response is not an empty value and record is not found in "Customerlist" 

(“CustomerList”)。范围(“B:B”),响应)<1

  Sheets("CustomerList").Range("B1048576").End(xlUp).Offset(1, 0).Value = response MsgBox "'" & response & "' successfully entered!"** Case Else MsgBox "Field is empty!" Call addNewCust_Click End Select End Sub 

喜欢这个?

 Sub addNewCust_Click() Dim response As String response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2) Select Case response Case False: Exit Sub 'Check if response is not an empty value AND record found in "CustomerList" Case Is <> "" If WorksheetFunction.CountIf(Worksheets("CustomerList").Range("B:B"), response) > 0 Then MsgBox "'" & response & "' already exists on this sheet." Call addNewCust_Click Else Sheets("CustomerList").Range("B1048576").End(xlUp).Offset(1, 0).Value = response MsgBox "'" & response & "' successfully entered!" End If Case Else MsgBox "Field is empty!" Call addNewCust_Click End Select End Sub 

跟随(从评论)

Select Case被认为比If-Endif快,但是对于这样的小场景,效率比较是徒劳的。 更重要的是你如何编写代码

下面是另一种方式。 我喜欢这种方式,因为事情被分解成更小的部分,一切都被正确地声明。 我没有触及下面的error handling。 看到这个详细的分析 。

下面的方法是有用的,因为

  1. 当你在看你的代码(也许在一年后),并且你知道自从代码被评论以来到底发生了什么。
  2. 易于维护的代码。 例如,如果工作表名称发生更改,则只能在一处更改。 另一种方法是也使用Codenames
  3. 您可以在所有Excel平台上使用相同的代码。 如果您对范围进行硬编码,例如: Range("B1048576")则上述代码在Excel 2003中将不起作用。

示例代码

 Sub addNewCust_Click() Dim ws As Worksheet Dim Lrow As Long Dim response '~~> Set the relevant worksheet Set ws = ThisWorkbook.Worksheets("CustomerList") With ws Do '~~> Get user response response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2) Select Case response Case False: Exit Sub '<~~ If user presses cancel or closes using 'X' Case "": MsgBox "Field is empty!" '<~~ If user enters a blank entry Case Else '~~> Check if the entry exists If WorksheetFunction.CountIf(.Range("B:B"), response) > 0 Then MsgBox "'" & response & "' already exists on this sheet." Else '~~> Get last Row Lrow = .Range("B" & .Rows.Count).End(xlUp).Row + 1 '~~> Add the new entry .Range("B" & Lrow).Value = response MsgBox "'" & response & "' successfully entered!" Exit Do 'OR Exit Sub (As Applicable) End If End Select Loop End With End Sub