Relative instead of Absolute paths in Excel VBA

前端 未结 8 937
眼角桃花
眼角桃花 2020-12-05 04:10

I have written an Excel VBA macro which imports data from a HTML file (stored locally) before performing calculations on the data.

At the moment the HTML file is ref

8条回答
  •  北海茫月
    2020-12-05 04:29

    I think the problem is that opening the file without a path will only work if your "current directory" is set correctly.

    Try typing "Debug.Print CurDir" in the Immediate Window - that should show the location for your default files as set in Tools...Options.

    I'm not sure I'm completely happy with it, perhaps because it's somewhat of a legacy VB command, but you could do this:

    ChDir ThisWorkbook.Path
    

    I think I'd prefer to use ThisWorkbook.Path to construct a path to the HTML file. I'm a big fan of the FileSystemObject in the Scripting Runtime (which always seems to be installed), so I'd be happier to do something like this (after setting a reference to Microsoft Scripting Runtime):

    Const HTML_FILE_NAME As String = "my_input.html"
    
    With New FileSystemObject
        With .OpenTextFile(.BuildPath(ThisWorkbook.Path, HTML_FILE_NAME), ForReading)
            ' Now we have a TextStream object that we can use to read the file
        End With
    End With
    

提交回复
热议问题