如何在宏编程中获取当前目录名?

时间:2012-10-25 11:59:24

标签: excel vba excel-vba

我需要知道如何在宏编程中获取当前目录变量。我在桌面上保存一个文件,如下所示:C:\ Users \ deadlock \ Desktop \ data.html。是否可以用当前的直接变量替换C:\ Users \ deadlock \ Desktop \?

这是我的一小段代码:

 ActiveWorkbook.ShowPivotChartActiveFields = True
With ActiveWorkbook.PublishObjects.Add(xlSourceSheet, _
    "C:\Users\deadlock\Desktop\data.htm", "Sheet1", "", xlHtmlStatic, "data_9438", "")
    .Publish (True)
    .AutoRepublish = False

任何代码段都将受到高度赞赏。

提前致谢..

2 个答案:

答案 0 :(得分:4)

当前目录可通过VBA的curdir()&通过ActiveWorkbook.Path获取当前工作簿的目录。

编辑;

Dim current As String
current = CurDir$()
'// root dirs have a \ others do not; normalize
If Right$(current, 1) <> "\" Then current = current & "\"

With ActiveWorkbook.PublishObjects.Add(xlSourceSheet, _
    current & "data.htm", "Sheet1", "", xlHtmlStatic, "data_9438", "")
    .Publish (True)
    ....

答案 1 :(得分:1)

  

是否可以用当前的直接变量替换C:\ Users \ deadlock \ Desktop \?

这是你在尝试的吗?

Option Explicit

Sub Sample()
    Dim strPath As String
    Dim Myar As Variant

    strPath = "C:\Users\deadlock\Desktop\data.htm"

    Myar = Split(strPath, "\")

    '~~> This would give you something like
    '~~> C:\Users\Siddharth Rout\Documents\data.htm
    Debug.Print CurDir & "\" & Myar(UBound(Myar))
End Sub