0

我已经记录并完善了以下宏,它应该创建一个额外的表,其中超文本链接指向原始表中每个表的起始单元格,称为“All_tables”。在此工作表中,每个表都由井号 (#) 分隔。 看截图

Sub Create_list_of_tables()

Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "list of tables"

ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
    "All_Tables!A22", TextToDisplay:="some variable pointing at the table name"
Range("A2").Select
End Sub

现在我想把它放到一个循环中,它会重复十次(或更多次)。我尝试使用井号作为程序的参考点,以找出他应该将超链接指向哪个单元格。结果如下:

Sub Create_list_of_tables()    
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "list of tables"

Const cStrDivider As String = "#"

Dim rMyCell As Range
Dim table_number As Long
table_number = 0


Do Until table_number = 10
Set rMyCell = Range("cStrDivider").Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
    "All_Tables!&rMyCell", TextToDisplay:="some variable pointing at the table name"
ActiveCell.Offset(1, 0).Select
table_number = table_number + 1
Loop

End Sub

它不起作用。我对宏和 VB 编程完全陌生,所以如果你至少能告诉我方向,我会非常高兴。我的方法是完全错误的吗?

非常感谢

4

1 回答 1

1

我不确定您希望超链接指向的确切位置,但这应该让您有一个良好的开端。需要注意的事项:

  • 不要使用SelectorSelection语句。它们很慢并且会产生不良影响。取而代之的是使用非常明确的陈述,这些陈述不依赖于光标位置,而是评估你知道事物所在位置的绝对位置。
  • 使用范围对象的FindandFindNext方法来定位字符串。当FindNext找不到更多内容时,它会返回nothing。最好检查而不是执行 table_number 循环。

更新

Sub Create_list_of_tables()

    Const cStrDivider As String = "#"

    Dim sht As Worksheet, rMyCell As Range, rSearchRange As Range
    Dim testSht As Worksheet, firstMyCell As Range

    Set sht = ActiveSheet

    On Error Resume Next
    Set testSht = ActiveWorkbook.Sheets("All_Tables")
    If Err.Number <> 9 Then
        Application.DisplayAlerts = False
        testSht.Delete
        Application.DisplayAlerts = True    'important to set back to true!
    End If
    On Error GoTo 0

    ActiveWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
    ActiveWorkbook.Sheets(Sheets.Count).Name = "All_Tables"

    Set rSearchRange = sht.Range("A:A")

    'do initial "Find"
    Set rMyCell = rSearchRange.Find(cStrDivider)
    Set firstMyCell = rMyCell

    Do
        sht.Hyperlinks.Add Anchor:=rMyCell.Offset(0, 1), Address:="All_Tables!" & rMyCell.Address, _
            TextToDisplay:="Link"

        'get the next "MyCell" to use from the master range to search
        Set rMyCell = rSearchRange.FindNext(rMyCell)
        'increment your table counter (if you want to do this you can still
        table_number = table_number + 1
        Debug.Print firstMyCell.Address
        Debug.Print rMyCell.Address
    Loop While firstMyCell.Address <> rMyCell.Address

End Sub

从那里开始,看看它是如何工作的。

于 2013-02-25T20:12:30.473 回答