为什么我的 VBA If 语句抛出类型不匹配错误

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

我有一个正在为项目构建的 VBA 函数,并且 if 语句不断抛出类型不匹配错误。这是相关代码:

Dim conn As ADODB.Connection
Set conn = New ADODB.Connection

With conn
  .ConnectionString = "DRIVER={SQL Server};SERVER=ATNSQL;DATABASE=PRGMAIN;Trust_Connection=yes;" ' connection to ATNSQL server
End With
    
conn.Open

Dim year_goal As ADODB.Recordset

sls_rep_wb.Worksheets(yy & " MO-MO").Activate
           
Set year_goal = conn.Execute("SOME SQL QUERY THAT RETURNS A SUM NUMERIC")
            
            
If IsEmpty(Range("AY3")) & year_goal.RecordCount > 0 Then ' this line throws the error
    Range("AY3:" & Range("AY3").Offset(0, 12).Address).Value = (year_goal!Sum) / 12
End If

起初,我收到一个错误,表明其中一次迭代返回了year_goal的空记录集,这就是我在记录计数条件中添加的原因。我尝试使用 BOF 和 EOF 属性来检查空记录集,但它们给出了相同的错误。即使记录集不为空,此代码也会引发错误。不知道是什么问题,请帮忙。谢谢!

excel vba adodb
1个回答
0
投票

运算符“&”仅适用于字符串。

下面这句话:

如果 IsEmpty(范围("AY3")) &year_goal.RecordCount > 0 那么

应该这样写:

If IsEmpty(Range("AY3")) Andyear_goal.RecordCount > 0 then

参考资料: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/and-operator

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ampersand-operator

© www.soinside.com 2019 - 2024. All rights reserved.