在VBA中的单元格之间移动图像

Tim*_*Tim 8 excel vba excel-vba

我在单元格(3,1)中有一个图像,并希望将图像移动到单元格(1,1)中.

我有这个代码:

ActiveSheet.Cells(1, 1).Value = ActiveSheet.Cells(3, 1).Value
ActiveSheet.Cells(3, 1).Value = ""
Run Code Online (Sandbox Code Playgroud)

但是,对于包含图像的单元格,单元格值似乎为空,因此不会移动图像,也不会删除单元格(3,1)中的图像.当我运行代码的特定位时,什么也没发生.

任何帮助是极大的赞赏.

谢谢.

Ben*_*ack 7

您的代码的部分问题在于您将图像视为单元格的.但是,虽然图像可能看起来像是在"单元格"中,但实际上并不是单元格的值.

移动图像,你可以这样做比较(使用Shape.IncrementLeftShape.IncrementRight),或者你可以做到这一点绝对(通过设置的值Shape.LeftShape.Top).

在下面的示例中,我演示了如何将形状移动到新的绝对位置,无论是否保持原始单元格的原始缩进(如果您没有保留原始缩进,这就像设置Top和的Left值一样简单)在Shape等于与目标的Range).

此过程采用形状名称(您可以通过多种方式找到形状名称;我这样做的方式是记录宏,然后单击形状并移动它以查看它生成的代码),目标地址(例如"A1",和(可选)一个布尔值,指示是否要保留原始缩进偏移量.

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
Run Code Online (Sandbox Code Playgroud)

注意:我以非常实用的方式编写代码.如果您想"清理"此代码,最好将功能放在对象中.希望它能帮助读者理解形状在Excel中的工作方式.