在VBA中处理#NA值

问题描述 投票:0回答:1

我编写了VBA代码,它根据列值在Sheet1函数的帮助下将数据从Sheet2复制到Match

Match函数抛出错误,因为Sheet2列中没有某些值,所以我尝试使用以下代码:

On Error Resume Next

代码将数据从Sheet1复制到Sheet2,但是当代码找不到Match时,它也将最后一列的相同值插入到下一列中。

所以我尝试使用以下代码来处理#NA错误:

cont = Application.WorksheetFunction.IsNA(Excel.WorksheetFunction.Match(Sheet2.Cells(1, i), Sheet1.Range("A3:Ah3"), 0))

但是代码本身开始抛出错误,当我尝试同时使用这两个代码时,cont变量值总是为false。

该问题的完整代码如下:

Sub Copy()
Dim lastColumnSheet2 As Long
Dim i As Long
Dim temp As Long
Dim cont As Boolean


lastColumnSheet2 = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column

On Error Resume Next
For i = 2 To lastColumnSheet2
    'cont = Application.WorksheetFunction.IsNA(Excel.WorksheetFunction.Match(Sheet2.Cells(1, i), Sheet1.Range("A3:Ah3"), 0))
    'If cont = False Then
    temp = Excel.WorksheetFunction.Match(Sheet2.Cells(1, i), Sheet1.Range("A1:Ah1"), 0)


        If Sheet2.Cells(2, i).Value = "" Then
                Sheet2.Cells(2, i).Value = Sheet1.Cells(2, temp).Value

        End If
    'Else
    'End If

Next i

任何人都可以指导我如何处理VBA中的#NA错误?

这是使用代码示例数据的链接:https://drive.google.com/file/d/1-luUAqleKgxcg4pWl_Mn4ecI9HrjnJAq/view?usp=sharing

excel vba match lookup worksheet
1个回答
1
投票

不确定代码的其余部分,只是为了说明如何处理可能由Match函数返回的错误。将temp声明为变量,以便在返回时可以存储错误值。使用Application.Match,它可以返回错误值而不会产生混乱。测试temp是否与IsError有误,然后相应地采取行动。

Option Explicit
Public Sub CopyInfo()
    Dim lastColumnSheet2 As Long
    Dim i As Long
    Dim temp As Variant
    Dim cont As Boolean

    lastColumnSheet2 = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column

    For i = 2 To lastColumnSheet2

        temp = Application.Match(Sheet2.Cells(1, i), Sheet1.Range("A1:AH1"), 0)

        If Not IsError(temp) And IsEmpty(Sheet2.Cells(2, i)) Then
            Sheet2.Cells(2, i).Value = Sheet1.Cells(2, temp).Value
        End If
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.