Excel VBA:创建新工作表的超链接

时间:2016-04-19 16:11:46

标签: excel vba

想知道这是否可行,但是:

所以我得到了一个宏按钮,可以从UserForm中将值插入到工作表中,这是一个可视化的示例,它看起来如何:

<table style="width:100%">
  <tr>
    <td>OrderID:</td>
    <td>Product</td> 
    <td>Q</td>
    <td>Invoice</td>
  </tr>
  <tr>
    <td>1</td>
    <td>Potato</td> 
    <td>1337</td>
    <td><a href="url">Open Invoice</a></td>
  </tr>
</table>

我使用此代码创建的“打开发票”链接:

    Sheets("Sales").Hyperlinks.Add Sheets("Sales").Cells(emptyRow, 9), "", Sheets("Sales").Name, "", "Open Invoice"

我想,每当我点击“打开发票”时,它会创建一个新的工作表(最好是一个新的Excel窗口),然后数据传输到一个模板(传输和模板,我想我会管理自己)< / p>

谢谢!

1 个答案:

答案 0 :(得分:3)

执行此操作以设置超链接:

Dim hlRange as Range
Set hlRange = Sheets("Sales").Cells(emptyRow, 9)
With hlRange.Hyperlinks
    .Delete
    .Add Anchor:=hlRange, _
         Address:="", _
         SubAddress:=hlRange.Address, _
         TextToDisplay:="Open Invoice"
End With

这会创建一个链接回自身的超链接,因此它是有效的引用,但它不会转到其他地方

然后,使用Worksheet_FollowHyperlink事件过程从您的模板创建一个新的工作簿,然后您可以根据需要插入数据:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim wb as Workbook
Dim ws as Worksheet
' If there are other hyperlinks in this sheet which should NOT trigger the new file, then you will need to add an Intersect test and exit sub early.

'Add a new workbook
Set wb = Workbooks.Open("path to template file")  '## Modify as needed
Set ws = wb.Worksheets(1)                         '## Modify as needed

'Add the data to the new sheet in new workbook
'  -- code here, or call another procedure to do the operation --

End Sub