常用自定義函式001 VBA高容錯性地開啟檔案

2021-05-23 01:33:17 字數 1569 閱讀 8658

**:

function openexcelfile(spath as string, byval sfilename as string, bdisplay as boolean, spwd as string) as integer

'開啟excel檔案

'ver 1.05

'完成時間:2007.12.01

'設計:美猴王軟體工作室 www.okexcel.com.cn

'引數說明:

'spath:檔案絕對路徑;sfilename:excel檔名;bdisplay:true顯示錯誤資訊;spwd:檔案開啟密碼

'返回值:-1:同名檔案已經開啟;-2:檔案不存在或密碼錯誤;0:成功開啟;1:檔案已經被開啟

dim bopen as boolean

dim sfullname as string

on error resume next

if instr(lcase(sfilename), ".xls") = 0 then sfilename = sfilename & ".xls"

sfullname = workbooks(sfilename).fullname

'檢查是否已經開啟同名的excel檔案

'如果有sfullname不為空

on error goto 0

bopen = false

if sfullname <> "" then

if lcase(sfullname) = lcase(spath & "/" & sfilename) then

bopen = true

'判斷已經開啟的同名檔案是否本次需要開啟的檔案

openexcelfile = 1

'檔案已經被開啟

else

if bdisplay then

msgbox "請首先關閉「" & sfilename & "」檔案!" & chr(13) & "不能同時開啟同名檔案,這是excel的規定!", vbokonly + vbexclamation, "檔案的開啟錯誤"

end if

bopen = true

openexcelfile = -1

'不能同時開啟同名檔案,這是excel的規定

end if

end if

if not bopen then

on error goto erropen

workbooks.open filename:=spath & "/" & sfilename, password:=spwd

on error goto 0

openexcelfile = 0

'成功開啟檔案

end if

exit function

erropen:

if bdisplay then msgbox err.description, vbokonly + vbexclamation, "檔案的開啟錯誤"

openexcelfile = -2

'檔案不存在或密碼錯誤

on error goto 0

end function

他山之石 VBA自定義函式

vba自定義函式自己是最近才開始使用的。其好處是可在工作表中直接呼叫,很方便。這裡,這位老師總結的很好,學習了!1 什麼是自定義函式?在vba中有vba函式,我們還可以呼叫工作表函式,我們能不能自已編寫函式呢?可以,這就是本集所講的自定義函式 2 怎麼編寫自定義函式?我們可以按下面的結構編寫自定義函...

VBA使用者自定義函式

函式是一組可重複使用的 可以在程式中的任何地方呼叫。這消除了一遍又一遍地編寫相同的 的需要。這使程式設計師能夠將乙個大程式劃分成許多小的可管理的功能模組。除了內建函式外,vba還允許編寫使用者定義的函式。乙個vba函式可以有乙個可選的return語句。如果要從函式返回值,則可使用return語句。例...

VBA自定義函式 Minkowski距離

接觸vba第一天,寫了個閔可夫斯基距離 當r 1時,距離為曼哈頓距離 當r 2時,距離為歐幾里得距離距離 直線距離 當r 時,距離為切比雪夫距離 根據閔可夫斯基距離距離公式,在vba寫出以下 public function distance a as range,b as range,optiona...