我有一张图片在单元格(3,1)中,想把它移动到单元格(1,1)。
这是我的代码:
ActiveSheet.Cells(1, 1).Value = ActiveSheet.Cells(3, 1).Value
ActiveSheet.Cells(3, 1).Value = ""
然而,对于包含图像的单元格,单元格的值似乎为空,因此图像未被移动,且单元格(3,1)中的图像未被删除。运行代码时没有任何反应。
非常感谢您的帮助。
谢谢。
Sub ShapeMove(strShapeName As String, _
strTargetAddress As String, _
Optional blnIndent As Boolean = True)
Dim ws As Worksheet
Dim shp As Shape
Dim dblCurrentPosLeft As Double
Dim dblCurrentPosTop As Double
Dim rngCurrentCell As Range
Dim dblCurrentCellTop As Double
Dim dblCurrentCellLeft As Double
Dim dblIndentLeft As Double
Dim dblIndentTop As Double
Dim rngTargetCell As Range
Dim dblTargetCellTop As Double
Dim dblTargetCellLeft As Double
Dim dblNewPosTop As Double
Dim dblNewPosLeft As Double
'Set ws to be the ActiveSheet, though this can really be any sheet '
Set ws = ActiveSheet
'Set the shp variable as the shape with the specified shape name '
Set shp = ws.Shapes(strShapeName)
'Get the current position of the image on the worksheet '
dblCurrentPosLeft = shp.Left
dblCurrentPosTop = shp.Top
'Get the current cell range of the image '
Set rngCurrentCell = ws.Range(shp.TopLeftCell.Address)
'Get the absolute position of the current cell '
dblCurrentCellLeft = rngCurrentCell.Left
dblCurrentCellTop = rngCurrentCell.Top
'Establish the current offset of the image in relation to the top left cell'
dblIndentLeft = dblCurrentPosLeft - dblCurrentCellLeft
dblIndentTop = dblCurrentPosTop - dblCurrentCellTop
'Set the rngTargetCell object to be the address specified in the paramater '
Set rngTargetCell = ws.Range(strTargetAddress)
'Get the absolute position of the target cell '
dblTargetCellLeft = rngTargetCell.Left
dblTargetCellTop = rngTargetCell.Top
'Establish the coordinates of the new position. Only indent if the boolean '
' parameter passed in is true. '
' NB: The indent can get off if your indentation is greater than the length '
' or width of the cell '
If blnIndent Then
dblNewPosLeft = dblTargetCellLeft + dblIndentLeft
dblNewPosTop = dblTargetCellTop + dblIndentTop
Else
dblNewPosLeft = dblTargetCellLeft
dblNewPosTop = dblTargetCellTop
End If
'Move the shape to its new position '
shp.Top = dblNewPosTop
shp.Left = dblNewPosLeft
End Sub
注意:我用一种非常功能化的方式编写了代码。如果您想要“清理”这段代码,最好将功能放在一个对象中。无论如何,希望它能帮助读者理解Excel中形状的工作方式。
Public Sub Example()
MoveShape ActiveSheet.Shapes("Picture 1"), Range("A1")
End Sub
Private Sub MoveShape(ByVal shp As Excel.Shape, ByVal target As Excel.Range)
shp.IncrementLeft -(shp.TopLeftCell.Left - target.Left)
shp.IncrementTop -(shp.TopLeftCell.Top - target.Top)
End Sub