VBA:将超链接添加到工作表中的单元格

时间:2019-02-21 17:37:12

标签: excel vba hyperlink excel-2016

我的目标是在添加新行时,我想将第一列中lastrow +1中的单元格链接到与该值具有相同名称的工作表。即将使用客户ID 130添加新客户,并使用相同的名称创建工作表。现在,我想添加一个从客户ID到工作表的链接。从用户表单输入中检索数据。也许我应该注意,在我的用户表单中单击命令按钮后,该子项就会运行。

在下面的代码中使用我在最后一行得到错误 ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:=Sheets(cs_sht), TextToDisplay:=cs_sht ,在此我收到错误'5无效的过程或参数'。 我尝试使用带有和不带有选择的锚点,以及将工作表和锚点更改为活动单元。

Private Sub CB_NewCS_Click()
'Copying data to table

Dim rng As Range
Dim LastRow As Long
Dim cs_sht As String
Dim ws As Worksheet
Dim Ws_K As Worksheet

NewCS.Hide

' Setting ranges and sheets
Set rng = Sheets("Kundeliste").ListObjects("Tabel_Kunde").Range
Set Ws_K = Sheets("Kundeliste")

' Searching for new input line
LastRow = rng.Find(What:=Ó * Ó, _
After:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row

' Inserting userform data
With rng.Parent
    .Cells(LastRow + 1, 1).Value = Application.WorksheetFunction.Max(rng.Columns(1)) + 1 ' Customer ID in ascending order
    .Cells(LastRow + 1, 2).Value = TB_Firstname.Value ' First name
    .Cells(LastRow + 1, 3).Value = TB_Lastname.Value ' Last name
    .Cells(LastRow + 1, 4).Value = TB_Phone.Value ' Phone number
    .Cells(LastRow + 1, 5).Value = TB_Address.Value ' Address
    .Cells(LastRow + 1, 6).Value = TB_Housenr.Value ' House / road number
    .Cells(LastRow + 1, 7).Value = TB_Floornr.Value ' Floor nr.
    .Cells(LastRow + 1, 8).Value = TB_Zipcode.Value ' Zipcode / postal code
    .Cells(LastRow + 1, 9).Value = TB_City.Value ' City / town
    .Cells(LastRow + 1, 10).Value = LB_Product.Value ' Product for the customer
    ' Checkbox values:
    .Cells(LastRow + 1, 12).Value = -Chb_Contact.Value
    .Cells(LastRow + 1, 13).Value = -Chb_Meet1.Value
    .Cells(LastRow + 1, 14).Value = -Chb_Accept.Value
    .Cells(LastRow + 1, 15).Value = -Chb_Meet2.Value
    .Cells(LastRow + 1, 16).Value = -Chb_Revision.Value
    .Cells(LastRow + 1, 17).Value = -Chb_Contact2.Value
    .Cells(LastRow + 1, 18).Value = -Chb_Followup.Value
    cs_sht = .Cells(LastRow + 1, 1).Value
End With

With ThisWorkbook
    Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    ws.Name = cs_sht
End With
Ws_K.Activate
Ws_K.Range(Ws_K.Cells(LastRow + 1, 1), Ws_K.Cells(LastRow + 1, 1)).Select
' OBS OBS OBS ERROR OCCURS HERE vvvvvvvv
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:=Sheets(cs_sht), TextToDisplay:=cs_sht


End Sub

2 个答案:

答案 0 :(得分:3)

您需要某种形式的东西:

SubAddress: = somestring

喜欢:

SubAddress:= "Sheet2!B9"

字符串表示工作表单元格组合。

答案 1 :(得分:3)

子地址必须是指向单元格的字符串,因此您需要类似

的内容
SubAddress:=cs_sht & "!A1"

宏记录器对于确定这种语法很有用。

相关问题