为什么我的vba脚本将所有超链接一起更改,而不是单独更改



首先我不擅长vba,我用了很多教程,但这不是我想要的;)

我正在努力实现的目标:选择电子表格中的超链接范围,并设置超链接以调用另一个从A2到AX的电子表格单元格(始终)(取决于我选择的行数)。(很抱歉没有正确命名,我上次使用vba大约是10年前)

在运行脚本之前:所有超链接都设置到不同的电子表格以调用单元格A2,如下所示:CommLinkItem_57!A2

重要提示:它不能使用=HYPERLINK(cell;name)函数,因为另一个脚本正在使用此电子表格,它不能与此函数一起使用

运行脚本后:超链接不会从A2增加到AX,而是所有超链接(我未选择的事件)都在调用最后一个迭代元素,该元素为AX

Sub LoopSelection()
Dim cel As Range
Dim selectedRange As Range
Dim aa As String
Dim counter As Integer
counter = 2
Set selectedRange = Application.Selection
For Each cel In selectedRange.Cells
Debug.Print cel.Address & " " & cel.Hyperlinks.Count
If cel.Hyperlinks.Count > 0 Then
aa = cel.Hyperlinks.Item(1).SubAddress
If cel.Hyperlinks.Item(1).SubAddress Like "*!*" Then
cel.Hyperlinks.Item(1).SubAddress = Trim(Split(aa, "!")(0)) & "!A" & counter
End If
counter = counter + 1
Debug.Print cel.Hyperlinks.Item(1).SubAddress
End If
Next cel
End Sub

例如,我从I10I20选择10个单元格,然后运行一个脚本。。我在控制台中的输出是这样的:

$I$10 1
CommLinkItem_57!A2
$I$11 1
CommLinkItem_57!A3
$I$12 1
CommLinkItem_57!A4
$I$13 1
CommLinkItem_57!A5
$I$14 1
CommLinkItem_57!A6
$I$15 1
CommLinkItem_57!A7
$I$16 1
CommLinkItem_57!A8
$I$17 1
CommLinkItem_57!A9
$I$18 1
CommLinkItem_57!A10
$I$19 1
CommLinkItem_57!A11
$I$20 1
CommLinkItem_57!A12

(工作正常,找到正确的单元格(I10:I20),找到一个超链接,找到名为CommLinkItem_57的电子表格,并设置(在控制台输出中)从A2A12的正确递增单元格值

因此,在excel中,I10I20单元调用CommLinkItem_57!A12。这是个问题。。你能指出我在哪里犯了错误吗,以及如何解决这个问题

您的代码还可以。问题是工作表维护了不同URL的HyperLinks集合。我怀疑你最初的URL都是一样的,所以你总是更新同一个HyperLink,最后得到一个计数器值最高的。如果可能,使您的初始URL不同。

据我所见,计数器应该不符合条件。像这样:

For Each cel In selectedRange.Cells
counter = counter + 1
Debug.Print cel.Address & " " & cel.Hyperlinks.Count
If cel.Hyperlinks.Count > 0 Then
aa = cel.Hyperlinks.Item(1).SubAddress
If cel.Hyperlinks.Item(1).SubAddress Like "*!*" Then
cel.Hyperlinks.Item(1).SubAddress = Trim(Split(aa, "!")(0)) & "!A" & counter
End If
Debug.Print cel.Hyperlinks.Item(1).SubAddress
End If
'or put the counter here, it depends on your code...
Next cel

就像@Excelosaurus所说的,所有的超链接都是类似引用的,当我更改一个超链接时,所有超链接也都更改了。因此,我制定了变通办法,并从基础上创建超链接:

  1. 我从A2计数到AX,所以计数器设置为2
  2. 嵌套单元格所在的表的名称总是在索引2中的同一列中,因此表名称设置所选范围的行2和列,并取单元格的值,即tableName
  3. 超链接仅在活动工作表中创建,行:With Worksheets(Application.ActiveSheet.Index)
  4. 如果我们不想将地址设置为url或文件,请设置address属性,即空引号""

我认为rest在代码中是不言自明的:

Sub LoopSelection()
Dim selectedRange As Range
Dim counter As Integer
Dim tableName As String
counter = 2
Set selectedRange = Application.Selection
tableName = Cells(2, selectedRange.Column).Value
For Each cel In selectedRange.Cells
With Worksheets(Application.ActiveSheet.Index)
.Hyperlinks.Add Anchor:=.Range(cel.Address), _
Address:="", _
SubAddress:=tableName & "!A" & counter, _
TextToDisplay:=tableName
End With
counter = counter + 1
Next cel
End Sub

最新更新