Excel VBAtypes不匹配#N / A
我有这块代码
With Data.Cells(rowMatch, GWECol) .Value = Cmp.Cells(i, GWENetPr) .AddComment .Comment.Text Text:=UCase(Environ("UserName")) & ":" & vbNewLine _ & "Comment: " & Cmp.Cells(i, CommCol) & vbNewLine _ & "Transaction: " & Cmp.Cells(i, QRTran) & vbNewLine _ & "QR Pr: " & Cmp.Cells(i, QRPr) & vbNewLine _ & "QR WD: " & Cmp.Cells(i, QRWD) & vbNewLine _ & "QR WD All: " & Cmp.Cells(i, QRWDA) & vbNewLine _ & "QR XPr: " & Cmp.Cells(i, QRXPr) & vbNewLine _ & "QR XAll: " & Cmp.Cells(i, QRXAll) & vbNewLine _ & "GWE Pr: " & Cmp.Cells(i, GWEPr) & vbNewLine _ & "GWE All: " & Cmp.Cells(i, GWEAll) & vbNewLine _ & "GWE XPr: " & Cmp.Cells(i, GWEXPr) & vbNewLine _ & "GWE XAll: " & Cmp.Cells(i, GWEXAll) .Comment.Shape.TextFrame.AutoSize = True End With
其中Cmp.Cells(i,X)是指可能有#N / A错误(失败的VLOOKUP)的单元。
是否有可能让代码只是把#N / A作为一个string,或者把它留空? 现在,只要有一个被引用的单元是#N / A,块就会失败,根本不会添加任何注释文本。
谢谢!
您正在使用单元格的默认属性,
Debug.Print Cmp.Cells(i, QRXAll)
例如,这总是指单元格.Value
属性。 .Value
实际上是一个错误types, Error 2042
,我认为你可以通过检查来避免
CLng(Cmp.Cells(i,QRXA11))
但是这将导致2042
而不是2042
#N/A
文本。
如果你想得到stringCmp.Cells(i, QRXAll).Text
#N/A
:尝试使用Cmp.Cells(i, QRXAll).Text
,它依赖于单元格的.Text
属性而不是.Value
。
Debug.Print Cmp.Cells(i, QRXAll).Text
免责声明:我已经做了一些VBA编程,但我不会称自己是一个专家。
这可能过于简单化,但您可以将每个值分配给一个variables,然后将variables分配给注释。 如果有任何一个值是N / A,至less其余的值仍然会被分配给注释。 我倾向于这种解决scheme,因为它可以确保一个错误不会影响整个操作。
Dim vComment As String Dim vTransaction As String Dim vQRPr As String Dim vQRWD As String ' Etc. vComment = Cmp.Cells(i, CommCol).Text vTransaction = Cmp.Cells(i, QRTran).Text vQRPr = Cmp.Cells(i, QRPr).Text vQRWD = Cmp.Cells(i, QRWD).Text ' Etc. .Comment.Text Text:=UCase(Environ("UserName")) & ":" & vbNewLine _ & "Comment: " & vComment & vbNewLine _ & "Transaction: " & vTransaction & vbNewLine _ & "QR Pr: " & vQRPr & vbNewLine _ & "QR WD: " & vQRWD & vbNewLine ' Etc.
编辑:感谢大卫指出应该使用.Text
属性
使用IsError来检查单元格是否有#N / A
if IsError(Cmp.Cells(i, GWENetPr)) then 'give it a valid value else 'use the value int he cell end if 'start with statement
例
With Data.Cells(rowMatch, GWECol) If IsError(Cmp.Cells(i, GWENetPr)) Then .Value = "" 'or #N/A Else .Value = Cmp.Cells(i, GWENetPr) End If .AddComment .Comment.Text Text:=UCase(Environ("UserName")) & ":" & vbNewLine _ & "Comment: " & Cmp.Cells(i, CommCol) & vbNewLine _ & "Transaction: " & Cmp.Cells(i, QRTran) & vbNewLine _ & "QR Pr: " & Cmp.Cells(i, QRPr) & vbNewLine _ & "QR WD: " & Cmp.Cells(i, QRWD) & vbNewLine _ & "QR WD All: " & Cmp.Cells(i, QRWDA) & vbNewLine _ & "QR XPr: " & Cmp.Cells(i, QRXPr) & vbNewLine _ & "QR XAll: " & Cmp.Cells(i, QRXAll) & vbNewLine _ & "GWE Pr: " & Cmp.Cells(i, GWEPr) & vbNewLine _ & "GWE All: " & Cmp.Cells(i, GWEAll) & vbNewLine _ & "GWE XPr: " & Cmp.Cells(i, GWEXPr) & vbNewLine _ & "GWE XAll: " & Cmp.Cells(i, GWEXAll) .Comment.Shape.TextFrame.AutoSize = True End With
如果出现错误,则可以使用IIf
来使用特定值:
& "Comment: " & IIf(IsError(Cmp.Cells(i, CommCol)),"",Cmp.Cells(i, CommCol)) & vbNewLine _