避免在Excel VBA中出现 #NV 值

huangapple go评论69阅读模式
英文:

avoid #NV values with excel vba

问题

我已经编写了这段代码:

thisworkbook.Sheets("test_destination").Range("J2:K" & lastrow_orgid).Value = Application.WorksheetFunction.Unique(diesesworkbook.Sheets("test_source").Range("J2:K" & lastrow_orgid).Value)

它执行了它应该执行的操作,但会创建这些 #NV 值。也许有人可以告诉我是否有另一种方法来编写这个以避免这些 #NV 值。

英文:

I have written this piece of code:

thisworkbook.Sheets("test_destination").Range("J2:K" & lastrow_orgid).Value = Application.WorksheetFunction.Unique(diesesworkbook.Sheets("test_source").Range("J2:K" & lastrow_orgid).Value)

It does what it is supposed to do but it creates these #NV values. Maybe someone could tell me if there is another way to write this to avoid these #NV values.

避免在Excel VBA中出现 #NV 值

避免在Excel VBA中出现 #NV 值

答案1

得分: 0

  1. 与对象一起工作。这将使您的生活更容易。
  2. 您假设返回的范围将具有与输入范围相同的宽度,因此您会收到该错误。
  3. 将唯一的值存储在数组中,然后将数组输出到相关范围。

这是一个示例。根据需要进行修改。

Option Explicit

Sub CriarBotaoLaranja()
    Dim ArOutput As Variant
    Dim wsA As Worksheet
    Dim wsB As Worksheet
    Dim lastrow_orgid As Long
    
    '~~> 根据需要更改工作表
    Set wsA = ThisWorkbook.Sheets("test_destination")
    Set wsB = ThisWorkbook.Sheets("test_source")
    
    '~~> 将此值硬编码。根据需要更改
    lastrow_orgid = 10
    
    '~~> 获取数组中的唯一值
    ArOutput = WorksheetFunction.Unique(wsB.Range("J2:K" & lastrow_orgid).Value)
    
    '~~> 将结果输出到相关范围
    wsA.Range("J2").Resize(UBound(ArOutput), 2).Value = ArOutput
End Sub

实际操作

避免在Excel VBA中出现 #NV 值

英文:

Couple of things.

  1. Work with objects. This will make your life easier.
  2. You are assuming that the returned range will have the same width as the input range and hence you are getting that error.
  3. Store the unique values in an array and then output the array to the relevant range.

Here is an example. Amend as applicable.

Option Explicit

Sub CriarBotaoLaranja()
    Dim ArOutput As Variant
    Dim wsA As Worksheet
    Dim wsB As Worksheet
    Dim lastrow_orgid As Long
    
    '~~> Change the worksheets as applicable
    Set wsA = ThisWorkbook.Sheets("test_destination")
    Set wsB = ThisWorkbook.Sheets("test_source")
    
    '~~> Harcoding this value. change as applicable
    lastrow_orgid = 10
    
    '~~> Get the unique values in an array
    ArOutput = WorksheetFunction.Unique(wsB.Range("J2:K" & lastrow_orgid).Value)
    
    '~~> Output the result to the relevant range
    wsA.Range("J2").Resize(UBound(ArOutput), 2).Value = ArOutput
End Sub

In Action

避免在Excel VBA中出现 #NV 值

huangapple
  • 本文由 发表于 2023年3月3日 19:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定