2017-01-17 115 views
0

我有這個問題,你可以返回一個excel的實例/對象在sub中使用嗎 我的意思是不是一次又一次地寫同一個代碼每次我需要打開一個Excel文檔。我想調用一個函數,即打開Excel這樣的事情你可以返回一個excel對象在Sub中使用嗎

Public Function TestExcel(ByVal filePath As String) As Object 

Dim oExcel As Object 
Dim oBook As Object 
Dim oSheet As Object 

Set oExcel = CreateObject("Excel.Application") 
Set oBook = oExcel.Workbooks.Open(filePath) 
Set oSheet = oBook.Sheets(1) 

Set TestExcel = oSheet 

End Function 
Sub test() 
Dim oSheet As Object 
Set oSheet = TestExcel("C:\Users\MYfile") 
test = oSheet.Range("B" & excelRow).Value 
'Or something like this 
number = 10 
osheet.Range("B" & excelRow).Value = number 
End Sub 

回答

0

function functionname(args) as excel.workbook,並在此功能中,一般朝着端,您可以使用您的文章

例如說set functionname = oBook

Function OpenWorkBook(strPath as string) as Excel.workbook 
    set OpenWorkbook=workbooks.open (strPath) 
end function 

及其用途

dim x as excel.workbook 
set x=openworkbook("c:\test.xlsx") 
+0

這就是它,非常感謝你 – CarstenW

相關問題