excel - VBA 触发工作表更改与复制/粘贴
问题描述
我正在尝试使用 VBA 根据工作表同一行上 B 列的值使用图像文件填充电子表格 G 列。如果我手动将值输入到 B 列中,一切正常,但是我有一个很长的列表,并希望将多个值复制/粘贴到 B 列中。当我粘贴时,似乎没有触发工作表更改并且未填充 H 列与图像。我正在使用的代码如下,任何帮助将不胜感激。谢谢!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim shp As Shape
If Intersect(Target, [B:B]) Is Nothing Then Exit Sub
If Target.Row Mod 20 = 0 Then Exit Sub
On Error GoTo son
For Each shp In ActiveSheet.Shapes
If shp.Type = msoPicture And shp.TopLeftCell.Address = Target.Offset(0, 4).Address Then shp.Delete
Next
If Target.Value <> "" And Dir(ThisWorkbook.Path & "\" & Target.Value & ".jpg") = "" Then
'picture not there!
MsgBox Target.Value & " Doesn't exist!"
End If
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 5).Top
Selection.Left = Target.Offset(0, 5).Left
With Selection.ShapeRange
.LockAspectRatio = msoFalse
.Height = Target.Offset(0, 5).Height
.Width = Target.Offset(0, 5).Width
End With
Target.Offset(1, 0).Select
son:
End Sub
解决方案
当您粘贴多个值时,Target
参数变为您粘贴的范围数组。如果仅粘贴 1 行,它也是 1 个成员的数组。
因此,使用For..Next
循环来完成您粘贴的所有行。并将所有更改Target
为Target(i)
并更改一些代码,如下所示。
For i = 1 To Target.Rows.Count
If Target(i).Value <> "" And Dir(ThisWorkbook.Path & "\" & Target(i).Value & ".jpg") = "" Then
'picture not there!
MsgBox Target(i).Value & " Doesn't exist!"
Else
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target(i).Value & ".jpg").Select
Selection.Top = Target(i).Offset(0, 5).Top
Selection.Left = Target(i).Offset(0, 5).Left
With Selection.ShapeRange
.LockAspectRatio = msoFalse
.Height = Target(i).Offset(0, 5).Height
.Width = Target(i).Offset(0, 5).Width
End With
End If
Next
推荐阅读
- javascript - 响应式网格仅从行中最后一个单元格的高度设置行高,而不是从行中最高的单元格
- html - 在 div 中渲染 CSS 背景图像以获得响应式视图
- javascript - 如何在字符串中的第二个逗号之后提取信息并删除它前面的内容?
- javascript - 从 yarn.lock 添加或删除包 URL “.git”
- git - 运行 `git update-index --assume-unchanged 后似乎仍会跟踪文件
` - python - 熊猫:如何转置数据框的一部分
- python - Jenkins 中的 os.environ 变量返回 None
- sql - 如何通过两个不同的标准对 sql server 数据进行排序
- r - 为什么 R 中的 na.omit 用 0 替换所有内容?
- sql - 有没有办法在 SQL 中查找具有正向序列值的列?