正在运行vba宏,出现错误,原因是“对象变量或未设置块变量”

时间:2018-08-09 04:21:41

标签: excel vba excel-vba ms-office

请找到我要运行的VBA代码。我知道我收到此错误。因为当我运行macro1()时,我正在调用一个尚未初始化/声明的变量。有没有一种方法可以在过程调用之前初始化公共变量。

在这方面帮助我。如果我理解不正确,请纠正我。

注意:我正在将其作为Excel加载项运行。

Public bugr As Variant
Public bugr_sheet As Variant
Public bugr_cell As Variant
Public scr As Variant

Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+e

'Getting current cell address
Set bugr_sheet = ActiveSheet
Set bugr_cell = ActiveCell
bugr = ActiveSheet.Name & "!" & ActiveCell.Address

'Creating dummy link
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
    bugr, TextToDisplay:="NA"

End Sub
Sub Macro2()
'
' Macro2 Macro
'
' Keyboard Shortcut: Ctrl+l
'
scr = ActiveSheet.Name & "!" & ActiveCell.Address
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
    bugr, TextToDisplay:=bugr

    bugr_sheet.Activate
    bugr_cell.Activate
    Selection.Hyperlinks(1).SubAddress = scr
    Selection.Hyperlinks(1).TextToDisplay = scr
   End Sub

2 个答案:

答案 0 :(得分:0)

我的解决方案:

首先在工作簿中的任何地方创建一个名为“ Origin”的命名范围。 为此,请转到名称管理器>新建...>将名称设置为“来源”,然后单击“确定”

完成后,您可以单击任何单元格并运行它:

Sub Store_Cell()

ActiveWorkbook.Names("Origin").RefersToR1C1 = ActiveCell

End Sub

然后单击任何其他单元格并运行它:

Sub hyperlink()

Dim OSh As Worksheet: Set OSh = Range("Origin").Parent
Ori = OSh.Name & "!" & Range("Origin").Address
Tar = ActiveCell.Parent.Name & "!" & ActiveCell.Address
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:=Ori, TextToDisplay:="Text"
OSh.Hyperlinks.Add Anchor:=Range("Origin"), Address:="", SubAddress:=Tar, TextToDisplay:="text2"

End Sub

答案 1 :(得分:0)

在Macro2中,您可以检查bugr_sheet是否为空,如果是,则设置空变量:

Sub Macro2()
'
' Macro2 Macro
'
' Keyboard Shortcut: Ctrl+l
'
    If IsEmpty(bugr_sheet) Then
        Set bugr_sheet = Worksheets("someSheetName") 'change "someSheetName" to your actual relevant sheet name
        Set bugr_cell = bugr_sheet.Range("someRangeReference") 'change "someRangeReference" to your actual relevant sheet range address
        bugr = bugr_sheet.Name & "!" & bugr_cell.Address
    End If

    scr = ActiveSheet.Name & "!" & ActiveCell.Address
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:=bugr, TextToDisplay:=bugr

    bugr_sheet.Hyperlinks.Add Anchor:=bugr_cell, Address:="", SubAddress:=scr, TextToDisplay:=scr    
End Sub