excel - 双击一个单元格以使用 VBA 显示来自 Excel 中链接的图片
问题描述
我有以下功能,如果您将鼠标移到它上面,它会显示一张图片。它非常整洁,效果很好。但是,我想将其从在其上运行鼠标更改为双击功能。
以下是当您在单元格上运行鼠标时将显示图片的代码:
Dim DoOnce As Boolean
Public Function OnMouseOver(URL As String, TheCell As Range)
DoOnce = True
With ActiveSheet.Pictures.Insert(URL)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 570
.Height = 380
End With
.Left = Cells(TheCell.Row, TheCell.Column + 1).Left
.Top = Cells(TheCell.Row, TheCell.Column + 1).Top
.Placement = 1
.PrintObject = True
End With
End Function
而且我知道我需要下面的代码,如果你双击它会发生一些事情:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Address = "$A$1" Then
'do something
End If
Cancel = True
End Sub
我似乎无法将两者合并-以便获得原始代码的功能,但需要双击而不是将鼠标移到单元格上。
初始代码按顺序为我的计算机上的图片引用一个串联的图片查找地址以进行处理。随着更多图片的生成,我用公式复制新的链接,这快速、简单、容易,这就是为什么我要保留初始代码的“OnMouseOver”功能,这样我就可以轻松地将其复制到新的单元格中。我只想将图片显示为双击,而不是像当前工作那样在单元格上运行鼠标。
如果我能帮上忙,那将是一个很大的帮助。
谢谢,
史蒂夫
解决方案
当“双击”进入 Excel 单元格的编辑时,可能会导致对现有值/公式的不希望的编辑。所以,我会推荐Worksheet_SelectionChange
活动。您也可以将它与导航/箭头键一起使用。
将以下代码粘贴到 VBA - 相关的“工作表”对象
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim url As String
On Error Resume Next 'to avoid error if the target cell does not have url
'Even if we can use URLExists function to avoid such error,
'there will still be errors when there is value but not recognised by the function.
'For example an error caused by function =100/0
ActiveSheet.Pictures.Delete
'If URLExists(Target.Value) Then
'As we are using "on error resume next statement we don't need this.
'here is a link to this function
'https://stackoverflow.com/a/25428811/9808063
url = Target.Value
With Me.Pictures.Insert(url)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 300
.Height = 200
End With
.Left = Cells(Target.Row + 2, Target.Column + 1).Left
.Top = Cells(Target.Row + 2, Target.Column + 1).Top
.Placement = 1
.PrintObject = True
End With
'End If
End Sub
推荐阅读
- adal - Azure AD 客户端凭据刷新访问令牌
- image - 使用 Microsoft Graph 从 Sharepoint 帖子中获取图像
- javascript - 如何在 string.match 中添加循环值?
- arduino - 尝试将代码上传到 NodeMcu 时出错,这将使我能够控制 LED 矩阵
- azure - PDI 缓慢加载到 Azure 数据库中
- android - 为什么这个问题“无法在线程内创建处理程序”发生在实时数据库上?
- robotframework - Robot Framework Input Text 未输入所有文本
- reactjs - 在组件外部访问的 Redux 存储返回初始状态
- ruby-on-rails - 为什么带有 S3 的 ActiveStorage 会提高 InvalidBucketName
- tfs - 将史诗转移到另一个项目