声明一个适用于Workbooks的变量()

时间:2015-09-23 16:43:09

标签: excel vba excel-vba

我希望在一个工作簿中构建一个宏(' master'工作簿),它将从我的计算机上的其他工作簿中获取代码并将其粘贴到主工作簿中。

我是新手,但据我所知,在您选择范围,复制数据等之前必须先打开工作簿。

我希望能够做的是将所有工作簿的路径分配给变量,以便我可以轻松地调用它们/读/写它们。我试图做的事情在下面的代码中说明

Sub MasterMacro()

    Dim MasterFile, File1 As Workbook

    Set File1 = Workbooks.Open("D:\test\folder1\file1.xlsx")

    Workbooks(File1).Range("A1").Value = "Help!"

End Sub

然而,这会产生运行时错误' 13' - 尝试更改A1的值时键入不匹配。

1 个答案:

答案 0 :(得分:2)

要修复代码,请将最后一行更新为:

File1.Worksheets("Sheet1").Range("A1").Value = "Help!"

更多详情:

Option Explicit

Private Const WBM_PATH  As String = "D:\test\folder1\"      'Module-level constant
Private Const WBM_NAME  As String = "file1.xlsx"

Private Const WBM_ERR   As String = "Unable to open Master file"
Private Const BR        As String = vbCrLf & vbCrLf

Private wbM As Workbook, wsM As Worksheet, urM As Range     'Module-level variables

Public Sub MasterMacro()
    If wbM Is Nothing Then
        If Len(Dir(WBM_PATH, vbDirectory)) > 0 Then             'If folder exists
            If Len(Dir(WBM_PATH & WBM_NAME)) > 0 Then           'If file exists
                Set wbM = Workbooks.Open(WBM_PATH & WBM_NAME)   'Set all Master objects
                Set wsM = wbM.Worksheets("Sheet1")
                Set urM = wsM.UsedRange
                urM.Cells(1, 1).Value2 = "Test"                 'Set text in Cell A1

                'copy value from file1.xlsx into the file executing the code
                ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = urM.Cells(1, 1)

                'copy a new value from original file into file1.xlsx
                ThisWorkbook.Worksheets("Sheet1").Range("A2") = "Test2"
                urM.Cells(2, 1) = ThisWorkbook.Worksheets("Sheet1").Range("A2")

                wbM.Close True  'close file1.xlsx, saving changes
            Else
                MsgBox "File '" & WBM_PATH & WBM_NAME & "' doesn't exist" & BR & WBM_ERR
            End If
        Else
            MsgBox "Folder '" & WBM_PATH & "' doesn't exist" & BR & WBM_ERR, , WBM_ERR
        End If
    End If
End Sub