循环添加超链接引用正确的单元格坐标,但在错误的工作表上

此代码旨在在当前表单上find与“主”表单元格对应的单元格,然后插入在两个单元格之间以双向方式工作的超链接。 两个超链接上显示的实际文本应该是在“主”表单元格中find的数字值。

我一直遇到两个问题:

一个。 '此属性或方法不支持对象'错误(下面提到的行位置)

湾 '插入超链接到正确的坐标,但在当前表中,而不是'主'

我在网上看到的所有例子使用sheet.hyperlink.add所以我很困惑,为什么我收到这个错误使用相同的语法

这是我的代码到目前为止

Sub hyperlinkinsert() Dim Sh As Worksheet Dim r As Range Dim R2 As Range Dim w As Range Dim W2 As Range Dim S1 As String Dim i As Integer i = 0 For Each Sh In ThisWorkbook.Worksheets i = i + 1 If i > 3 Then S1 = Sh.Cells(1, 1).Text Set r = Sh.Cells.Find(What:="Chosen Value") If Not r Is Nothing Then Set R2 = r.Offset(0, 1) Set w = Sheets("Main").Cells.Find(S1) If Not w Is Nothing Then Set W2 = w.Offset(0, 2) R2.Formula = "=Index('Main'!H12:H284,Match(A1,'Main'!F12:F284,0))" '**** ERROR MSG OCCURS HERE **** Sh.Hyperlinks.Add Anchor:=R2, Address:="", _ SubAddress:=Sheets("Main").W2, TextToDisplay:=R2.Value Sheets("Main").Hyperlinks.Add Anchor:=Sheets("Main").W2, _ Address:="", SubAddress:=R2, TextToDisplay:=Sheets("Main").W2.Value End If End If Set r = Nothing Set R2 = Nothing Set w = Nothing Set W2 = Nothing End If Next End Sub 

克里斯的答案解决scheme适用于代码,再加上一个:

 Option Explicit Sub hyperlinkinsert() Dim wsC As Worksheet, wsM As Worksheet, celC As Range, celM As Range, adr As String Set wsM = ThisWorkbook.Worksheets("Main") For Each wsC In ThisWorkbook.Worksheets If wsC.Index > 3 Then Set celM = wsM.UsedRange.Find(What:=wsC.Cells(1, 1).Text) Set celC = wsC.UsedRange.Find(What:="Chosen Value") If Not celM Is Nothing And Not celC Is Nothing Then Set celM = celM.Offset(0, 2) Set celC = celC.Offset(0, 1) adr = "'" & wsC.Name & "'!" & wsC.Cells(1, 1).Address celC.Formula = "=Index(Main!H12:H284,Match(" & adr & ",Main!F12:F284,0))" If Not IsError(celC) Then wsC.Hyperlinks.Add celC, "", celM.Address(External:=True) wsM.Hyperlinks.Add celM, "", celC.Address(External:=True) End If End If End If Next End Sub 

假设:公式中的单元格A1的值应从当前表单中提取

你的代码有两个问题

  1. 当使用一个Range对象时,它已经包含工作表上下文,例如Sheets("Main").W2而不是Sheets("Main").W2只使用W2

  2. Hyperlinks.Add方法, SubAddress参数需要是地址string,包括工作表引用。 例如,而不是SubAddress:=R2使用SubAddress:=R2.Address(External:=True)

把它放在一起,你的超链接代码应该是

 Sh.Hyperlinks.Add Anchor:=R2, Address:="", _ SubAddress:=W2.Address(External:=True), TextToDisplay:=R2.Value Sheets("Main").Hyperlinks.Add Anchor:=W2, Address:="", _ SubAddress:=R2.Address(External:=True), TextToDisplay:=W2.Value