我正在尝试在不同的工作簿之间复制数据。工作簿的名称碰巧是随机的,因为用户可以选择文件名,所以我在我的代码中做了一套工作簿。当我将一个子程序包含到我的程序中时,它表示下标超出了范围。
关于如何确保子程序继续理解我对工作簿的定义的任何想法?
如果您不太了解第一个潜在客户背后的基本原理,我的代码会被简化:
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
答案 0 :(得分:1)
你需要 wb 和 wb2 全球:
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