以下是我的宏的代码。问题是我的宏运行正常(执行查询并将数据放在电子表格上)但我收到此错误
运行时错误' 13'类型不匹配
宏执行查询并将数据放在电子表格中,但我在此行显示黄色突出显示的错误
Strcode = Target.Value
有什么建议吗?
Sub JobTaskHistory(ByVal Target As Range)
Dim sqlstring As String
Dim connstring As String
Dim Strcode As String
'Strcode = Trim(InputBox("Please enter a Job Number", "Job Task history"))
Strcode = Target.Cells(1, 1).Value
sqlstring = "select distinct m.JobNumber , cast(m.ExpectedDate as DATE) 'Ship Date' &_
" from ArchiveJobHeader m left join AuxiliaryInfoFile af (nolock) on af.jobnumber=m.jobnumber left join CostEntry ce (NOLOCK) on ce.sJobNumber = m.JobNumber left join CostCenterFile cc (nolock) ON cc.Code = ce.sDepartmentCode left join JobExtra j on j.JobNumber = m.JobNumber & _
" where m.JobNumber = '" & Trim(Strcode) & "'" & _
" order by 'Resulttime'"
connstring = "ODBC;DSN=Test;UID=Test;PWD=Test123"
Dim thisQT As QueryTable
Dim lastRow As Long, nextRow As Long
lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
nextRow = lastRow + 1
'Set thisQT = ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("a1", "a1000"))
Set thisQT = ActiveSheet.QueryTables.Add( _
Connection:=connstring, _
Destination:=Range("A" & nextRow))
thisQT.BackgroundQuery = False
thisQT.Sql = sqlstring
thisQT.Refresh
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Call JobTaskHistory(Target.Cells(1, 1).Value)
End Sub
答案 0 :(得分:1)
如果Range
(Target
)包含多个单元格,您将收到此错误。
例如:
Dim rangeTest As Range
Set rangeTest = Range("A1")
MsgBox rangeTest.Value ' This works.
Set rangeTest = Range("A1:B1")
MsgBox rangeTest.Value ' This fails with runtime 13 error.
所以要修复它,请确保您只引用单个单元格。为安全起见,您可以使用以下方法访问范围中的第一个单元格:
' This will work if Target is a single cell or multiple.
' It will always use the upper-left most cell in the range.
Strcode = Target.Cells(1, 1).Value
进行修改后更新
这会导致错误:
Private Sub Worksheet_Change(ByVal Target As Range)
Call JobTaskHistory(Target.Cells(1, 1).Value)
End Sub
因为您传递的是值而不是函数所需的Range
。用此替换该行,使其与JobTaskHistory
方法兼容:
Call JobTaskHistory(Target)