簡體   English   中英

如何使用 Excel VBA 宏設置 HTML 頁面標題?

[英]How do I set HTML page title using Excel VBA Macro?

  ActiveWorkbook.SaveAs Filename:= _
        "C:\example\Desktop\AutoOutput\test"+ ".html", _
        FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False

^要保存的宏腳本

我有一個 Excel 表格,我將其保存為 HTML 格式以供分享。

我想應用頁面標題(打開網頁時在瀏覽器選項卡/窗口中看到的內容)。 我知道您可以通過 excel 保存並通過手動保存獲得該選項

我如何通過宏來做到這一點?

網上找不到類似的問題

在此處輸入圖像描述

'auto save
       ChDir "C:\Example\AutoOutput\" + TestDate()
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Example\AutoOutput\" + TestDate() + "filename.html", _
        FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False
        

^將文件保存為html,通常

        
        
        'Declare ALL of your variables :)
     Dim fileToRead As String
     Dim fileToWrite As String
Const ForReading = 1    '
 fileToRead = "C:\Example\AutoOutput\" + TestDate() + "filename.html"   ' the path of the file to read
 fileToWrite = "C:\Example\AutoOutput\" + TestDate() + "filename.html"   ' the path of a new file
Dim FSO As Object
Dim readFile As Object  'the file you will READ
Dim writeFile As Object 'the file you will CREATE
Dim repLine As Variant   'the array of lines you will WRITE
Dim ln As Variant
Dim l As Long

Set FSO = CreateObject("Scripting.FileSystemObject")
Set readFile = FSO.OpenTextFile(fileToRead, ForReading, False)


'# Read entire file into an array & close it
repLine = Split(readFile.ReadAll, vbNewLine)
readFile.Close

'# iterate the array and do the replacement line by line
For Each ln In repLine
    ln = IIf(InStr(1, ln, "</head>", vbTextCompare) > 0, Replace(ln, "</head>", "</head><title>YOUR TITLE, FINALLY</title>"), ln)
    repLine(l) = ln
    l = l + 1
Next

'close excel (if not you cant overwrite)
        ActiveWorkbook.Close SaveChanges:=True
        
        Set writeFile = FSO.CreateTextFile(fileToWrite, True, False)
'# Write to the array items to the file
writeFile.Write Join(repLine, vbNewLine)
writeFile.Close

'# clean up
Set readFile = Nothing
Set writeFile = Nothing
Set FSO = Nothing

^這部分來自here ,但我對其進行了修改,以便它可以寫入當前文件而不是新文件

Workbooks.Open "C:\Example\AutoOutput\" + TestDate() + "filename.html"
 
    Shell "explorer.exe " + "C:\Example\AutoOutput\" + TestDate() + "filename.html"

^打開已完成的工作。

放置頁面標題的非常廣泛的步驟><

感謝 Code Scooper 在評論中的建議,我使用了他的建議如何在 VBA 中使用 FileSystemObject 替換文本文件行中的字符串? , 來嘗試我替換 1 個單數標簽的想法,

在這種情況下</head> ,並將其替換為自身 + 新標題: </head><title>YOUR TITLE, FINALLY</title>

我還稍微修改了代碼,以便我可以讓它能夠覆蓋自己。 因為我不想要 filename.html 和 filename2.html

不確定是否有更簡單的解決方案,如果有並且您碰巧找到它,請在此處添加。 現在我很高興它有效。 Filename:= "C:\Example\filename.html", FileFormat:=xlHtml, ...中沒有太多東西,可能就是這個解決方案。

編輯:編輯,以這種方式保存它時,我會丟失一些較小的字體顏色。即使我已經打開帶有標題的字體並再次保存,當字體顏色返回時,標題也會丟失。 看起來這是一個糟糕的臨時編輯,通過手動應用字體顏色而不是超鏈接類型來設法修復它。 整體方法很差。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM