仅从文件夹(路径)打开带有HTML扩展名的文件,而不提供文件名

时间:2018-02-09 01:51:55

标签: excel vba excel-vba

在特定路径中打开只有1extension的所有文件而不给出文件名。因为我在1个文件夹中有很多html文件,文件名不同但扩展名相同(.html)

我可以直接使用此代码打开,但需要提供文件名。我有多个具有不同名称和相同(.html)扩展名的文件,这使得很难打开这些文件1by1并提交条目

Set web = CreateObject("Shell.Application")
web.Open ("C:\Users\hp\Desktop\mani\hi.html")
Set web = Nothing

2 个答案:

答案 0 :(得分:3)

使用Dir命令循环浏览该文件夹中的所有* .html文件。

dim fn as string, fp as string, fm as string
dim web as object

Set web = CreateObject("Shell.Application")
fp = "C:\Users\hp\Desktop\mani\"
fm = "*.html"
fn = Dir(fp & fm)
do while cbool(len(fn))
    web.Open fp & fn
    'do something to the file here
    'close the open file here
    fn = Dir
loop

答案 1 :(得分:0)

或者您可以让用户选择所需的文件并逐个处理:

Sub PickHTMLFile()
    With Application.FileDialog(msoFileDialogFilePicker)
        .Filters.Add "Html files", "*.html", 2 ' add a filter #2
        .FilterIndex = 2 ' set initial file filter to the added one #

        .Show
        If .SelectedItems.Count > 0 Then
            Dim f As Variant
            For Each f In .SelectedItems 'loop through selected items
                'do your job here, as for example:
                MsgBox "Selected item's path: " & f 'show the current item path
                With CreateObject("Shell.Application")
                    .Open f
                End With
            Next
        Else
            MsgBox "user canceled file picker!"
        End If
    End With
End Sub