如何使用循环遍历Excel电子表格创建单独的HTML发布页面

时间:2013-04-23 00:06:19

标签: html excel excel-vba vba

我正在尝试使用Excel电子表格上的循环函数创建单独的HTML页面。我曾手动发布每个页面,但我有数千个条目,所以我需要一个使用宏的自动方法。我通过下面显示的手动方法记录了一个宏,其中包含我使用的步骤:

Sub HTMLexport()

Columns("A:W").Select
With ActiveWorkbook.PublishObjects.Add(xlSourceRange, _
    "C:\Users\<user_name>\Desktop\Excel2HTML\Articles\1045_VSE.htm", _
    "Sheet1", "$A:$W", xlHtmlStatic, _
    "FileName_10067", "")
    .Publish (True)
End With
Columns("W:W").Select
Selection.EntireColumn.Hidden = True
End Sub

最终我想要的是能够选择A列和下一列(例如B,C,H等),然后将这两个列发布到HTML页面中。我希望基于单元格引用的文件的名称。防爆。单元格W3的值为1045,文件名保存为1045_VSE.htm,其中_VSE在循环过程中是常量。这样,每个新的HTML页面名称将根据单元格引用递增。保存HTML页面后,隐藏列并移至下一列,冲洗并重复。对此的任何帮助都会很棒。提前致谢。

1 个答案:

答案 0 :(得分:0)

将它置于循环内应该相当简单。

这是一个例子。我假设文件名将来自子范围中的第一行/第二列,您可以轻松地修改它,或者问我如何修改。我还假设Div ID(“FileName_100067”)是常量。同样,如果需要,可以很容易地修改它。

Sub HTMLinLoop()
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet: Set ws = ActiveSheet
Dim rng As Range '##  The full range including all columns'
Dim subRng As Range '## a variable to contain each publishObjects range'
Dim pObj As PublishObject '## A variable to contain each publishObject as we create it.'
Dim p As Long '## use this integer to iterate over the columns in rng'
Dim fileName As String '## represents just the file name to export'
Dim fullFileName As String '## the full file path for each export'
Dim divName As String '## variable for the DivID argument, assume static for now'

Set rng = ws.Range("A3:W30") '## modify as needed'

For p = 1 To rng.Columns.Count
    'Identify the sub-range to use for this HTML export:'
    ' this will create ranges like "A:B", then "A:C", then "A:D", etc.'
    Set subRng = Range(rng.Columns(1).Address, rng.Columns(p + 1).Address)

    'Create the filename:'
    '## modify as needed, probably using a range offset.'
    fileName = subRng.Cells(1, 2).Value & "_VSE.htm"

    'Concatenate the filename & path:'
    '## modify as needed.'
    exportFileName = "C:\Users\" & Environ("Username") & "\Desktop\" & fileName

    'Create hte DIV ID:'
    divName = "FileName_10067" '## modify as needed, probably using a range offset.'

    '## Now, create the publish object with the above arguments:'
    Set pObj = wb.PublishObjects.Add( _
        SourceType:=xlSourceRange, _
        fileName:=exportFileName, _
        Sheet:=ws.Name, _
        Source:=subRng.Address, _
        HtmlType:=xlHtmlStatic, _
        DivID:=divName, _
        Title:="")

    '## Finally, publish it!'
    pObj.Publish

    '## Hide the last column:'
    rng.Columns(p+1).EntireColumn.Hidden = True

Next

End Sub