UserForm数据保存到工作表和word文档以及要添加到单元格的超链接

时间:2017-04-20 11:31:27

标签: excel-vba hyperlink vba excel

单击“提交”按钮时,Userform数据将保存到sheet3中的下一个可用行,并创建一个word文档并保存到特定文件夹中。

同时,如何添加刚创建的word文档文件名的超链接,并在H列中插入超链接?它可以添加到下面的代码中吗? 请有人帮忙吗?

SaveName = "\Desktop\DAILY REPORT" & Format(Now, "dd-mmm-yyyy") & FileExt
If .Version <= 12 Then
           .ActiveDocument.SaveAs SaveName
        Else
           .ActiveDocument.SaveAs2 SaveName
        End If
          .ActiveDocument.Close
        .Quit
        Set wdApp = Nothing      
End Sub

1 个答案:

答案 0 :(得分:0)

是。您可以设置超链接。以下代码可作为粗略指南。关键是您需要为要放置超链接的H列中的单元格提供行号。代码中有更多错误,因为您只提供了一小部分程序。目的是展示如何编程超链接。

Private Sub SetHyperlink()

    Const C As Long = 8                 ' = Column H

    Dim Wdapp As MSWord.Application
    Dim SaveName As String
    Dim Ws As Worksheet
    Dim Rng As Range
    Dim R As Long

    Set Ws = ActiveSheet                ' change as required
    R = Ws.Cells(Ws.Rows.Count, "H").End(xlUp).Row + 1
    ' the path of SaveName is incomplete:
    ' must start with drive (like C:\Users\[Username]\Desktop)
    ' or Environ("USERPROFILE") & "\Desktop
    SaveName = "\Desktop\DAILY REPORT" & Format(Now, "dd-mmm-yyyy") & FileExt

    Set Rng = Ws.Cells(R, C)
    Ws.Hyperlinks.Add Anchor:=Rng, _
                      Address:=SaveName, _
                      TextToDisplay:="Choose your text", _
                      ScreenTip:="Click to open the file"

    With Wdapp
        If .Version <= 12 Then
           .ActiveDocument.SaveAs SaveName
        Else
           .ActiveDocument.SaveAs2 SaveName
        End If

        .ActiveDocument.Close
        .Quit
    End With

    Set Wdapp = Nothing
End Sub