根据单元格中定义的名称定义工作簿

时间:2016-12-03 02:58:34

标签: excel vba excel-vba

  • 我想定义第二个工作簿的数据,以便其他宏可以使用活动工作簿中单元格A1中定义的名称来选择它。
  • Cell A1的文字为“openme”

我目前有:

Sub CrossCopyRangeSelect()

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Workbooks.Open Filename:=Range("A1").Value

Set x = ThisWorkbook
Set y = Workbooks(Filename:=Range("A1").Value)

End Sub

出错
Set y =

我不确定使用哪个函数来定义A1

中文本的工作簿名称

3 个答案:

答案 0 :(得分:1)

打开新书后,它将成为有效书:

Sub CrossCopyRangeSelect()
    Dim x As Workbook, y As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
    Set x = ThisWorkbook
    Workbooks.Open Filename:=Range("A1").Value
    Set y = ActiveWorkbook
End Sub

注:

我在单元格 A1

中有完整的文件规范

enter image description here

答案 1 :(得分:0)

错误是因为您可能需要从set y = workbooks(name)语句中的名称中删除文件的路径。

对代码的最简单修复是在open语句中指定y:

Set y = Workbooks.Open(Range("A1").Value)

答案 2 :(得分:0)

在打开文件之前清除以检查文件是否确实存在:

Sub CrossCopyRangeSelect()
    Dim Wb1 As Workbook
    Dim Wb2 As Workbook

    Set Wb1 = ThisWorkbook

    If Len(Dir(Wb1.Sheets(1).Range("A1").Value)) > 0 Then
        Set Wb2 = Workbooks.Open(Wb1.Sheets(1).Range("A1").Value)
    Else
        MsgBox "file doesnt exist"
    End If

End Sub