萬盛學電腦網

 萬盛學電腦網 >> Excel教程 >> excel綜合 >> Excel vba返回的路徑

Excel vba返回的路徑

   ①返回應用程序完整路徑

  Application.Path

  比如:D:SoftWareOffice2003OFFICE11

  ②返回當前工作薄的路徑

  ThisWorkbook.Path

  比如:D:

  ③返回當前默認文件路徑

  Application.DefaultFilePath

  比如:C:Documents and SettingsAdministratorMy Documents

  ④只返回路徑

  Application.ActiveWorkbook.Path

  比如:D:

  ⑤返回路徑及工作簿文件名

  Application.ActiveWorkbook.FullName

  比如:D:Book1.xls

  ⑥返回工作簿文件名

  Application.ActiveWorkbook.Name

  比如:Book1.xls

  上面的六種情況,在VBA環境下,你也可以通過如下的代碼測試:

  MsgBox Application.Path

  ActiveSheet.Cells(1, 1).Value = Application.Path

  MsgBox ThisWorkbook.Path

  ActiveSheet.Cells(2, 1).Value = ThisWorkbook.Path

  MsgBox Application.DefaultFilePath

  ActiveSheet.Cells(3, 1).Value = Application.DefaultFilePath

  MsgBox Application.ActiveWorkbook.Path

  ActiveSheet.Cells(4, 1).Value = Application.ActiveWorkbook.Path

  MsgBox Application.ActiveWorkbook.FullName

  ActiveSheet.Cells(5, 1).Value = Application.ActiveWorkbook.FullName

  MsgBox Application.ActiveWorkbook.Name

  ActiveSheet.Cells(6, 1).Value = Application.ActiveWorkbook.Name

  除此之外,和路徑有關的一個函數Dir,是專門用來判斷文件是否存在的函數,代碼如下:

  Application.ScreenUpdating = False

  With Application.FileSearch

  .FileType = msoFileTypeExcelWorkbooks

  .LookIn = ThisWorkbook.Path

  .SearchSubFolders = True

  .Execute

  If .Execute() > 0 Then

  m = .FoundFiles.Count '當前目錄及子目錄所有工作薄總數

  'MsgBox m

  For Each f In .FoundFiles '在所有的工作薄裡做一個循環

  'MsgBox Dir(f) '列出每個工作薄的名稱,只顯示名稱,如 dzwebs.xls ,無路徑

  If (Dir(f) <> "Total.xls") Then

  Set xlsApp = New Excel.Application

  Set xlsBook = Workbooks.Open(ThisWorkbook.Path & "" & Dir(f))

  Set MyWantGetsheet = xlsBook.Worksheets(1)

  For i = 1 To 8

  MyWantGetsheet.Cells(i, 6).Value = "www.dzwebs.net"

  Next i

  xlsBook.Save

  xlsBook.Close

  xlsApp.Quit

  Set xlsApp = Nothing

  Set xlsBook = Nothing

  Set MyWantGetsheet = Nothing

  Application.ScreenUpdating = True

  End If

  Next

  End If

copyright © 萬盛學電腦網 all rights reserved