我编写了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
不确定代码的其余部分,只是为了说明如何处理可能由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