excel - 有没有如何处理 vba 中的错误 13
问题描述
你好
我的 vlookup 一直有一个错误 13,当我在工作表上执行 vlookup 时,它很快就会起作用 vba 我不是在寻求帮助吗
这是我的代码,所有列都是我工作表中的文本
Sub address_change()
Dim updatesheet As Variant
Dim sbw As String
Dim Param As String
Dim entier As Integer
Dim fname As String
Dim tsk As Task
Dim rg As Variant
Dim ws As Sheets
Dim wb As Excel.Workbook
Dim appXLS As Object
Dim entxls As Object
Dim i As Integer
Set appXLS = CreateObject("Excel.Application")
If appXLS Is Nothing Then
MsgBox ("XLS not installed")
End If
fname = ActiveProject.Path & "\" & Dir(ActiveProject.Path & "\addresses.xlsx")
MsgBox (fname)Set wb = appXLS.Workbooks.Open(fname, False)
Set rg = appXLS.Worksheets("sheet2").Range("A:U")
appXLS.Visible = TrueMsgBox (appXLS.Application.Value)
On Error Resume Next
For Each tsk In ActiveProject.Tasks
Param = tsk.Text2
If tsk.OutlineLevel = 2 Then
updatesheet = appXLS.Application.VLookup(Param, rg, 16, False)
If Err.Number <> 0 Then
tsk.Text13 = "No match 32"
Else
tsk.Text13 = updatesheet
End If
End If
Next tsk
End Sub
解决方案
有两种方法可以在 VBA 中使用 Excel VLookup
(以及类似的函数,如Match
),它们有所不同。
Application.VLookup
如果找不到搜索词,(您正在使用的版本)将返回错误值 。Error 2042
这不是运行时错误,这是一个返回值。错误值是 VBA 中的一种特殊数据类型(它们不是字符串,Error 2042
只是它的表示形式)。准确地说,#N/A
如果 Vlookup 失败,您会在 Excel 中看到此错误。
您将结果写入 variable updatesheet
,这很好,因为它被声明为Variant
,并且变体可以保存错误值。但是,现在您检查是否发生了错误,因为事实并非如此,它会尝试将错误值分配给tsk.Text13
,这会给您一个类型不匹配的错误(我假设tsk.Text13
需要一个字符串)。
您需要检查是否updatesheet
包含错误值,而不是像您那样检查运行时错误,这是使用IsError
-function 完成的。在这种情况下,您还可以使用Application.IsNA()
-function。
另一种方法是使用WorksheetFunction.Vlookup
,如果找不到搜索词,这将引发运行时错误,您需要将其包装到错误处理中。
使用一种或另一种方法:
updatesheet = appXLS.VLookup(Param, rg, 16, False)
If appXLS.IsNA(updatesheet) Then
tsk.text13 = "No match 32"
Else
tsk.text13 = updatesheet
End If
updatesheet = "No match 32"
On Error Resume Next
updatesheet = appXLS.WorksheetFunction.VLookup(Param, rg, 16, False)
On Error GoTo 0
tsk.text13 = updatesheet
如需进一步阅读,我推荐https://rubberduckvba.wordpress.com/2021/02/15/worksheetfunction-and-errors/
推荐阅读
- postgresql - SaltStack:在特定更改时重新启动服务器(不仅重新加载)
- python - 在python中一次将相同的字符串参数传递给一个类的两个不同方法
- oracle - Spring boot Oracle JPA 设置 QueryTimeout
- php - 如何根据不同的任务显示日期时间间隔?
- javascript - 如何将两个元素一起存储在堆栈Javascript计算器中
- java - 如何记录方法的参数值
- python - Pytorch 可微分条件(基于索引)和
- google-chrome - Sec-Fetch-Mode 和阻塞的 CORS
- java - 如何使用 Java 修改现有 Excel 工作簿
- php - 如何向 WooCommerce 产品属性添加额外信息?