我正在尝试为我制作TFT(队战战术)表,并希望使其看起来更好。为此,我想添加游戏中冠军的图像。输入名称时,图像应显示在下方。我找到了一种将所有图像插入excel工作表(〜100)的方法,并且还成功制作了一个动态图像:
= insertIMG:
=INDEX(PIC!$B$1:$B$55;MATCH(Sheet1!B4;PIC!$A$1:$A$55;0))
我试图将 Sheet1!B4 部分变量设置为变量,但它不适用于单元格D5。现在对我而言,唯一的解决方案是为每个“插槽”创建一个“名称”范围,但这将花费大量时间。是否可以通过输入名称使excel在下面插入图像?
答案 0 :(得分:2)
Y 您可以使用Worksheet_Change
事件来实现所需的目标。
出于演示目的,我将使用3个单元格B4
,C4
和D4
假设我们的图片表(我们称其为PIC
)看起来像这样。
如果您注意到,我在第二行中插入了空白形状。如果用户在B4
,C4
或D4
中按下Delete键,我们将使用此形状。如果找不到匹配项,我们还将使用此图片。
现在让我们准备我们的主要工作表。请按照以下步骤操作
B2
工作表中选择单元格PIC
(不是形状),然后按 CRTL + C 。B5
,然后单击Paste Special-->Linked Picture
,如下所示。
C5
和D5
。您的工作表现在看起来像这样。
代码:
Option Explicit
'More about Worksheet_Change at the below link
'https://stackoverflow.com/questions/13860894/why-ms-excel-crashes-and-closes-during-worksheet-change-sub-procedure/13861640#13861640
Private Sub Worksheet_Change(ByVal Target As Range)
'~~> Check if multiple cells were changed
If Target.Cells.CountLarge > 1 Then Exit Sub
On Error GoTo Whoa
Application.EnableEvents = False
If Not Intersect(Target, Range("B4:D4")) Is Nothing Then
Dim wsPic As Worksheet
Dim pic As Shape, txtShp As Shape, shp As Shape
Dim addr As String
Dim aCell As Range
'~~> Identify the shape below the changed cell
For Each shp In ActiveSheet.Shapes
If shp.TopLeftCell.Address = Target.Offset(1).Address Then
Set txtShp = shp
Exit For
End If
Next shp
Set wsPic = ThisWorkbook.Sheets("PIC")
'~~> Find the text in the PIC sheet
Set aCell = wsPic.Columns(1).Find(What:=Target.Value2, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> Identify the shape
If Not aCell Is Nothing Then
For Each shp In wsPic.Shapes
If shp.TopLeftCell.Address = aCell.Offset(, 1).Address Then
Set pic = shp
addr = aCell.Offset(, 1).Address
Exit For
End If
Next shp
End If
'~~> Add the formula to show the image
If Not pic Is Nothing And Not txtShp Is Nothing Then
txtShp.Select '<~~ Required to insert the formula
Selection.Formula = "=PIC!" & addr
Else
txtShp.Select
Selection.Formula = "=PIC!$B$2"
End If
Target.Select '<~~ Remove focus from the shape
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
实际操作
示例文件
您可以从Here下载示例文件
答案 1 :(得分:1)
Function insertIMG(ByVal rng As Range)
Dim rng2 As String
rng2 = "$D$5" 'Application.Caller.Address (Now here is a hardcoded adress, the application.caller.address is a reference to the cell that called the function, and should be used when it's running as an UDF.)
Dim row As Integer
row = Application.WorksheetFunction.Match(rng, Sheets("PIC").Range("A1:A5"), 0)
Sheets("PIC").Range("B" & row).Copy
With Worksheets("Blad1")
'adapt worksheet name as appropriate
.Pictures.Paste(Link:=True).Select
End With
insertIMG = ""
End Function
如果我在选择D5的同时从一个子对象中调用此对象,它将插入一个链接的图像。我使用的这个SUB:
Sub test()
insertIMG(Application.Workbooks("Map1").Worksheets("Blad1").Range("D4"))
'adapt workbook and worksheet name as appropriate
End Sub
当我直接将其作为公式运行时,会出现一些错误。