如何在VBA中创建适当的循环(宏)

时间:2013-02-25 16:46:14

标签: excel vba excel-vba

我已经记录并打磨了下面的宏,它应该创建一个额外的工作表,其中超文本链接指向原始工作表中名为“All_tables”的每个表的起始单元格。在此工作表中,每个表都用井号(#)分隔。 See a screenshot

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编程都是全新的,所以如果你至少可以向我指明方向,我会非常高兴。我的做法完全错了吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

我不确定你的超链接指向哪里,但这应该会给你一个良好的开端。需要注意的事项:

  • 请勿使用SelectSelection语句。它们很慢并且会产生不良影响。而是使用非常明确的语句,这些语句不依赖于光标位置,而是评估你知道事物所处位置的绝对位置。
  • 使用范围对象的FindFindNext方法查找字符串。如果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

看看它是如何运作的。