excel - VBA 用户输入、复制公式和创建工作表的超链接
问题描述
我有一个按钮,要求用户输入和单元格选择。该按钮还会在表格底部插入一个新行,并且应该向下复制公式,但事实并非如此。当用户输入字符串时,它应该匹配工作簿中已经存在的工作表。所以我想将新单元格与现有工作表的名称匹配以创建超链接。那也不行。
Private Sub NewWellButton_Click()
Dim well As Variant
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
' Copy formula from cell above
Rows(Selection.Row).Insert Shift:=xlDown
ActiveCell.EntireRow.Copy
ActiveCell.EntireRow.PasteSpecial Paste:=xlPasteFormulas
Application.CutCopyMode = xlCopy
Dim ChosenRange As Range
Set ChosenRange = Application.InputBox(prompt:="Select the next empty cell in column A to input the well name.", Type:=8)
well = Application.InputBox("Enter the new well name", Title:="New Well")
ChosenRange.Value = UCase(well)
ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:=well
On Error Resume Next
MsgBox "Well names do not match to create hyperlink"
Exit Sub
End Sub
解决方案
超链接子地址需要指向工作表上的单元格,如“工作表名称”!A1。
Option Explicit
Private Sub NewWellButton_Click()
Dim wb As Workbook, ws As Worksheet, wsNew As Worksheet, sht As Worksheet
Dim sWellName As String, lastCell As Range, bExists As Boolean, s As String
Set wb = ActiveWorkbook
Set ws = wb.Sheets(1)
sWellName = Application.InputBox("Enter the new well name", Title:="New Well")
If Len(sWellName) = 0 Then
MsgBox "Well Name blank", vbExclamation
Exit Sub
Else
For Each sht In wb.Sheets
If sht.Name = sWellName Then bExists = True
Next
End If
If bExists = False Then
s = "Sheet [" & sWellName & "] does not exist, do you want to create it ?"
If vbYes = MsgBox(s, vbYesNo, "Not Found") Then
Set wsNew = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
wsNew.Name = sWellName
ws.Select
End If
End If
' copy
Set lastCell = ws.Cells(Rows.Count, 1).End(xlUp)
lastCell.EntireRow.Copy
' paste below
Set lastCell = lastCell.Offset(1, 0)
lastCell.PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
' add link
With lastCell
.Value = UCase(sWellName)
.Hyperlinks.Add Anchor:=lastCell, Address:="", SubAddress:="'" & sWellName & "'!A1"
End With
End Sub
推荐阅读
- kubernetes - 跨 GCP 项目在 GKE 集群中将 Google 服务帐户与 Kubernetes 集群服务帐户绑定
- angular - 使用 Firebase 刷新 accessToken
- excel - 通过根据条件转置数据,将数据从一个 workbbok 复制到另一个 workbbok
- data-warehouse - 星型设计反馈
- networking - 使用遗传算法的无线传感器网络路由协议
- javascript - 如何强制 JS 忽略一个 li 元素
- python - 在 Python 中按 MB 大小拆分日志数据
- r - 如何根据 R 中的列中的文本创建二进制变量?
- python - 如何加快迭代大型列表和求和值
- amazon-web-services - 根据字符串字段对 redis 哈希图进行排序