2009-12-15 3 views
8

У меня есть изображение в ячейке (3,1) и вы хотите переместить изображение в ячейку (1,1).Перемещение изображений между ячейками в VBA

У меня есть этот код:

ActiveSheet.Cells(1, 1).Value = ActiveSheet.Cells(3, 1).Value 
ActiveSheet.Cells(3, 1).Value = "" 

Тем не менее, кажется, что значение ячейки пусты для ячеек, содержащих изображения, так что поэтому изображение не перемещается, а изображение в ячейке (3,1) не является удален. Ничего не случилось, когда я запустил этот бит кода.

Любая помощь очень ценится.

Спасибо.

ответ

7

Часть проблемы с вашим кодом заключается в том, что вы думаете об изображении как значение соты. Однако, хотя изображение может оказаться «в» ячейке, на самом деле это не значение ячейки.

Чтобы переместить изображение, вы можете сделать это относительно (с использованием Shape.IncrementLeft или Shape.IncrementRight), или вы можете сделать это абсолютно (путем установки значения Shape.Left и Shape.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 

ПРИМЕЧАНИЕ.. Я написал код в очень функциональной манере Если вы хотел бы «очистить» этот код, было бы лучше разместить функциональность внутри объекта. Надеюсь, это поможет читателю понять, как формы работают в Excel в любом случае.

3

быстрый и грязный способ:

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 
Смежные вопросы