Excel 宏在执行 sql 查询后显示错误

Excel Macro displays error after executing sql query

下面是我的宏的代码。问题是我的宏运行良好(执行查询并将数据放在电子表格中)但我收到此错误

RunTime Error '13' Type Mismatch

宏执行查询并将数据放入电子表格,但我收到此行黄色突出显示的错误

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

如果您的 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)