宏或VBA中的动态工作簿和工作表名称

时间:2014-03-19 10:25:56

标签: excel vba excel-vba

我有这样的代码:(我目前正在使用Excel 2003)

Sub test_copy1()    

Dim wb1 As Workbook     
Dim wb2 As Workbook     
Dim ws1 As Worksheet     
Dim ws2 As Worksheet      

Set wb1 = Workbooks("Workbook2.xls")     
Set wb2 = ThisWorkbook     
Set ws1 = wb1.Sheets("Run 1")     
Set ws2 = wb2.Sheets("Sheet3") 

ws2.Range("A1:h30") = ws1.Range("A177:H206").Value  

End Sub

在当前的工作簿“表3”中 Cell J1 = Workbook2.xls 单元格J2 =运行1

如何将当前工作簿“工作表3”中的信息从单元格提供给宏,以便可以根据需要进行更改并仍然有效?

我的意思是让2个单元格可以在工作表中更改,可以通过下拉或手动填写当前工作簿表“工作表3”。 单元格:J1等于文件名(Workbook2.xls),J2等于工作表名称(运行1)。

用户可以在需要时更改文件名和工作表名称,然后点击按钮处理复制和粘贴。

我希望代码从单元格中获取信息并将它们放入代码中,而不是“硬编码”工作簿和工作表的文件名。

我希望这更有意义

感谢您的帮助。

~DA

----- ---- UPDATE

我已尝试过这段代码,但它仍然在第一个Set Wb1 =

上崩溃
    Sub test_copy1()

        Dim wb1 As Workbook
        Dim wb2 As Workbook
        Dim ws1 As Worksheet
        Dim ws2 As Worksheet

        Set wb1 = Workbooks(ws2.Range("J1"))
        Set wb2 = ThisWorkbook
        Set ws1 = wb1.Sheets(ws2.Range("J2"))
        Set ws2 = wb2.Sheets("Sheet3")

        ws2.Range("A1:h30") = ws1.Range("A177:H206").Value

    End Sub

------更新-------

我使用你所有的例子并在范围之后添加.Value让它工作:)

Sub test_copy1()

    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Set wb2 = ThisWorkbook
    Set ws2 = wb2.Sheets("Sheet3")

    Set wb1 = Workbooks(ws2.Range("J1").Value)
    Set ws1 = wb1.Sheets(ws2.Range("J2").Value)

    ws2.Range("A1:h30") = ws1.Range("A177:H206").Value

End Sub

谢谢,谢谢你的帮助!!

1 个答案:

答案 0 :(得分:3)

试试这个:

Sub test_copy1()

    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Set wb2 = ThisWorkbook
    Set ws2 = wb2.Sheets("Sheet3")

    Set wb1 = Workbooks(ws2.Range("J1").Value)
    Set ws1 = wb1.Sheets(ws2.Range("J2").Value)

    ws2.Range("A1:H30").Value = ws1.Range("A177:H206").Value

End Sub