2013-09-28 35 views
0

我試圖做不同的工作簿之間的數據副本。工作簿的名稱是隨機的,因爲用戶可以選擇文件名,所以我在我的代碼中做了一組工作簿。當我在程序中包含一個子程序時,它會將下標超出範圍。下標超出範圍錯誤的子程序

有關如何確保子例程能夠繼續理解我的工作簿定義的任何想法?

我的代碼的情況下,簡化您不太瞭解的第一子背後的理由:

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

清澈如泥。 :( – dotNET

+0

你在哪裏聲明'wb'和'wb2' for test123。如果我運行你的代碼時沒有'Option Explicit'設置,我得到一個'Object Required'錯誤。你確定'wb2'會有一個工作表命名'Sheet1'? –

+0

@DougGlancy你是對的,我再次嘗試了代碼,它顯示了運行時錯誤,而不是我說的那個..有點奇怪,我確定wb2有Sheet1。 – user1204868

回答

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

This ve rsion使用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 
+0

非常感謝!我學到了關於全局設置它們的另一件事 – user1204868

+2

這很糟糕你應該避免使用全局變量,除非必要,相反,將工作簿作爲變量傳遞給你的子程序,並且這並不回答原來的'下標超出範圍'問題 –

+1

Hi Doug:將它們作爲參數傳遞是一個好主意......我沒有考慮它......超出範圍的下標可能表示「Sheet1」v.s. 「Sheet 1」拼寫問題。 –