类型不匹配vba错误

时间:2017-11-23 21:37:24

标签: vba excel-vba excel

我正在尝试使用VBA替换电子表格中的链接,并且我遇到类型不匹配错误,无法找出原因。

我的代码:

    Dim aLinks as variant
    Dim myPath, name as String

aLinks = ActiveWorkbook.LinkSources
myPath = "C:\"
name = "test.xlsm"

    ActiveWorkbook.ChangeLink Name:=aLinks, NewName:=myPath & name, Type:=xlExcelLinks

有谁知道原因?

2 个答案:

答案 0 :(得分:2)

aLinks = ActiveWorkbook.LinkSources

那种类型是Variant()数组。

ActiveWorkbook.ChangeLink Name:=aLinks, NewName:=myPath & name, Type:=xlExcelLinks

...而且您无法将数组强制转换为String

您可能需要弄清楚该数组中的哪个项目包含您想要的名称。例如:

ActiveWorkbook.ChangeLink Name:=aLinks(1), NewName:=myPath & name, Type:=xlExcelLinks

答案 1 :(得分:1)

aLinks需要声明为String或强制转换为字符串Cstr(aLinks)。 Path也应声明为String,但因为您将它与String连接,所以它将被强制转换为字符串myPath & name

Workbook.ChangeLink Method (Excel)

Name    Required    String  The name of the Microsoft Excel or DDE/OLE link to be changed, as it was returned from the LinkSources method.
NewName Required    String  The new name of the link.
Type    Optional    XlLinkType  The link type.