2017-08-17 25 views
0

注意:我對查找工作表的路徑並不感興趣,我打算將該工作表的路徑寫入位於與.OTM文件相同的文件夾中的文本文件中。 我需要將此代碼從硬編碼路徑轉換爲從位於與宏相同文件夾中的文本文件中讀取的路徑。如何獲得使用宏(vba代碼)本身的宏的路徑?

如何獲得使用宏(vba代碼)本身的宏的路徑?

Public xlApp As Object 
Public xlWB As Object 
Public xlSheet As Object 
Sub OpenXl() 
    Dim enviro As String 
    Dim strPath As String 
enviro = CStr(Environ("USERPROFILE")) 
'the path of the workbook 
strPath = enviro & "\Documents\test2.xlsx" 
    On Error Resume Next 
    Set xlApp = GetObject(, "Excel.Application") 
    If Err <> 0 Then 
     Application.StatusBar = "Please wait while Excel source is opened ... " 
     Set xlApp = CreateObject("Excel.Application") 
     bXStarted = True 
    End If 
    On Error GoTo 0 
    'Open the workbook to input the data 
    Set xlWB = xlApp.Workbooks.Open(strPath) 
    Set xlSheet = xlWB.Sheets("Sheet1") 
    ' Process the message record 
    On Error Resume Next 
End Sub 
+0

1.找到告訴你的Excel文件的屬性。首先谷歌響應:https://stackoverflow.com/questions/2813925/how-to-get-the-path-of-current-worksheet-in-vba 2.更改'strPath'指的是,而不是 –

+1

可能的重複[如何獲取VBA中當前工作表的路徑?](https://stackoverflow.com/questions/2813925/how-to-get-the-path-of-current-worksheet-in-vba) – FatTony

+0

我是對找到工作簿的路徑不感興趣,我很想找到宏的路徑,所以我知道從哪裏讀取我的文本文件。 – NAlexP

回答

0

的OTM文件存儲在這裏我的電腦(Windows 7中/展望2010年):

strPath = Environ("userprofile") & "\AppData\Roaming\Microsoft\Outlook\" 
+0

是的,但沒有辦法找到使用ol vba腳本的路徑嗎?假設我在桌面上的一個文件夾中,然後將文件夾移動到我的文檔中或其他東西中。 – NAlexP

+0

我正在研究這個。據我可以告訴它幾乎必須在該版本的文件夾中,否則它不起作用。從Sue Moshers舊頁面:_All Outlook宏被存儲在用戶的%appdata%\ Microsoft \ Outlook folder_中的一個名爲VbaProject.otm的單個文件中。http://www.outlookcode.com/article.aspx?id=28 –

+0

因此,如果它沒有存儲在所述文件夾中宏宏不起作用? – NAlexP

0

只需使用:

ThisWorkbook.Path 

這將返回一個包含代碼的工作簿的路徑。

+0

我使用outlook vba,所以當我嘗試'debug.print thisworkbook.path'時,它給了我一個Object required錯誤。 – NAlexP

+0

但是,當我使用'debug.print xlWB.Path'時,它會向工作簿返回適當的路徑,但這對我沒有任何幫助。 – NAlexP

+0

參考https://stackoverflow.com/questions/233702/where-does-outlook-store-the-vba-code-files,它顯示Outlook代碼存儲在用戶的'%appdata%\ Microsoft \ Outlook'文件夾中。你想要得到什麼? – Olly