0

我正在尝试在不同的工作簿之间复制数据。工作簿的名称恰好是随机的,因为用户可以选择文件名,所以我在我的代码中做了一组工作簿。当我在我的程序中包含一个子例程时,它指出下标超出范围。

关于如何确保子例程继续理解我对工作簿的定义的任何想法?

如果您不太了解第一个 sub 背后的基本原理,我的代码会被简化:

Option Explicit
Sub testwe()
Dim wb As Workbook, wb2 As Workbook, vFile As Variant
Set wb = ActiveWorkbook 

vFile = Application.GetOpenFilename("Excel-files,*.xls", _
    1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
Set wb2 = ActiveWorkbook 'set the opened file as wb2

Call test123
End Sub

 sub test123()
 wb.Worksheets("Sheet1").Range("A1") = wb2.Worksheets("Sheet1").Range("B1")
 End Sub
4

1 回答 1

1

您需要使wbwb2全局化:

Dim wb As Workbook, wb2 As Workbook

Sub testwe()
    Set wb = ActiveWorkbook

    vFile = Application.GetOpenFilename("Excel-files,*.xls", _
        1, "Select One File To Open", , False)
    'if the user didn't select a file, exit sub
    If TypeName(vFile) = "Boolean" Then Exit Sub
    Workbooks.Open vFile
    Set wb2 = ActiveWorkbook 'set the opened file as wb2
    Call test123
End Sub

 Sub test123()
    wb.Sheets("Sheet1").Range("A1") = wb2.Sheets("Sheet1").Range("B1")
 End Sub

编辑#1

这个版本使用 Doug 的建议:

Sub testwe()
    Dim wb As Workbook, wb2 As Workbook
    Set wb = ActiveWorkbook
    vFile = Application.GetOpenFilename("Excel-files,*.xls", _
        1, "Select One File To Open", , False)
    'if the user didn't select a file, exit sub
    If TypeName(vFile) = "Boolean" Then Exit Sub
    Workbooks.Open vFile
    Set wb2 = ActiveWorkbook 'set the opened file as wb2
    Call test123(wb, wb2)
End Sub

 Sub test123(wb As Workbook, wb2 As Workbook)
    wb.Sheets("Sheet1").Range("A1") = wb2.Sheets("Sheet1").Range("B1")
 End Sub
于 2013-09-28T14:59:01.677 回答