【问题标题】:Add user entry if not a duplicate如果不重复,则添加用户条目
【发布时间】:2022-10-08 04:47:32
【问题描述】:

此代码的目标是接受用户输入的数字 (New_Project_Number),然后读取一个列表(A3 列到该列的最后一行)比较数字并检查重复项。然后将 New_Project_Number 粘贴到“A”列的最后一行。

Sub Project_Number_Standerdization()

Dim New_Project_Number As Variant
Dim Used_Project_Number As Variant
Dim Last_Pn As Integer 'this is a looping variable for the last row in column a
Dim wss As Worksheet
Dim ii As Integer

New_Project_Number = Application.InputBox("What is the New Project Number?", Type:=1)
Set wss = ActiveSheet
Last_Pn = wss.Range("A3").End(xlDown)


For ii = 1 To Last_Pn

Used_Project_Number = wss.Range("A3").Offset(ii - 1, 0).Value

If New_Project_Number = Used_Project_Number _
Then MsgBox ("That project number is being used please choose a different one.") _
Next ii 

End Sub

但是,这会检查是否有欺骗行为,但不会将代码发布到底部。如果我添加

Else wss.range("A3").end(Xldown).offset(1,0) 

在 then 语句之后和之前

Next ii

然后出现错误信息

“否则没有 if 语句”

如何检查所有使用的项目编号,然后在最后一个单元格上写下新项目编号。现在这只检查是否有欺骗性。

【问题讨论】:

  • 这个link 可能有用。
  • 因为在MsgBox 语句的末尾有一个续行符号_,VBA 认为Next 行是它的一部分。删除_,你应该会很好。
  • 此外,您真的很想阅读多行 If...End If 语法。
  • 谢谢大家的这些建议。多么棒的社区!

标签: excel vba


【解决方案1】:

使用Match() 会更快且无需循环:

Sub ProjectNumberStandardization()

    Dim New_Project_Number As Variant
    Dim m As Variant
    Dim wss As Worksheet
    
    Set wss = ActiveSheet
    
    New_Project_Number = Application.InputBox("What is the New Project Number?", Type:=1)
    m = Application.Match(New_Project_Number, wss.Columns("A"), 0)
    
    If IsError(m) Then 'no existing match?
        'add the number to the next empty cell at the bottom (xlUp is safer than xlDown)
        wss.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Value = New_Project_Number
    Else
        MsgBox "That project number is being used please choose a different one."
    End If
    
End Sub

【讨论】:

  • @TimWilliams OT:您对使用这种方法而不是声明范围变量并检查范围是否为空有什么看法?
  • @Sgdva - 你的意思是使用Find() 而不是Match()? Match 通常要快得多,所以除非我需要 Find() 提供的一些额外灵活性,否则我会默认使用它
  • @TimWilliams 谢谢:在这方面,如果 match 给出了一个数字,最好声明它,设置“on error resume next”,如果这个 'm' 变量是 0 意味着也没有现有的匹配?
  • @Sgdva - 这是另一种方法,是的,但是为什么不利用它在将返回分配给 Variant 时不会引发运行时错误的事实呢?捕获错误需要更多的工作......
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2015-05-23
相关资源
最近更新 更多