我的解法:
Public YesorNoKK As Boolean
Sub main() Dim Pname As String Dim Ntemp As String Dim Narray Dim Adg As Integer, InsetregS As Integer Dim my1 As Boolean, my2 As Boolean Dim r As Integer, c As Integer Dim a As Integer, b As Integer Dim Mnum As Integer Dim Myr1 As Integer, Myr2 As Integer, Myc1 As Integer, Myc2 As Integer, PSc As Integer Application.ScreenUpdating = False YesorNoKK = True IfKK If YesorNoKK = False Then Exit Sub Selection.HomeKey Unit:=wdLine With Application.Dialogs(wdDialogInsertPicture) Adg = .Show Ntemp = .Name End With If Adg <> -1 Then Exit Sub Narray = VBA.Split(Ntemp, "\", -1) Pname = VBA.Left(Narray(UBound(Narray)), VBA.Len(Narray(UBound(Narray))) - 4) '循环查找插入图片所在单元格 my1 = True my2 = True For r = 1 To 4 If r = 1 Or r = 3 Then For c = 1 To 5 a = Me.Tables(1).Rows(r).Cells(c).Range.End b = Me.Tables(1).Rows(r).Cells(c).Range.Start If a - b > 2 And my1 = True Then Myr1 = r: Myc1 = c: my1 = False If a - b = 1 And my2 = True And my1 = False Then Myr2 = r: Myc2 = c: my2 = False If my1 = False And my2 = True Then Mnum = Mnum + 1 Next End If Next If my2 = True Then MsgBox "单元格已满或者在插入点前有空单元格,无法插入图片": Me.Undo 1: Exit Sub With Me.Tables(1) PSc = Myc1 For r = Me.Tables(1).Range.InlineShapes.Count To Me.Tables(1).Range.InlineShapes.Count - Mnum - 1 Step -1 If Myr2 = 3 And Myc2 <> 1 Then Me.Tables(1).Rows(Myr2).Cells(Myc2 - 1).Range.Cut Me.Tables(1).Rows(Myr2).Cells(Myc2).Range.Paste Me.Tables(1).Rows(Myr2 + 1).Cells(Myc2 - 1).Range.Cut Me.Tables(1).Rows(Myr2 + 1).Cells(Myc2).Range.Paste End If If Myr2 = 3 And Myc2 = 1 Then Me.Tables(1).Rows(1).Cells(5).Range.Cut Me.Tables(1).Rows(3).Cells(1).Range.Paste Me.Tables(1).Rows(2).Cells(5).Range.Cut Me.Tables(1).Rows(4).Cells(1).Range.Paste End If If Myr2 = 1 Then Me.Tables(1).Rows(1).Cells(Myc2 - 1).Range.Cut Me.Tables(1).Rows(1).Cells(Myc2).Range.Paste Me.Tables(1).Rows(2).Cells(Myc2 - 1).Range.Cut Me.Tables(1).Rows(2).Cells(Myc2).Range.Paste End If
If Myc2 >= 1 Then Myc2 = Myc2 - 1 If Myc2 = 0 And Myr2 > 2 Then Myr2 = Myr2 - 2: Myc2 = 5 If Myr2 = 1 And Myc2 = PSc Then Exit For Me.UndoClear Next 'Debug.Print Myr2 & " " & Myc2 Addname = InputBox("请为插入的图片写上说明文字", "请输入", Pname) Me.Tables(1).Rows(Myr1 + 1).Cells(Myc1).Range.Text = Addname InsetregS = Me.Tables(1).Cell(Myr1, Myc1 + 1).Range.Start Me.Range(InsetregS, InsetregS + 1).Cut Me.Range(InsetregS - 1, InsetregS).Paste Application.ScreenUpdating = True End With End Sub Sub IfKK() '将光标下移一个单元格 Selection.EndKey Unit:=wdLine Selection.HomeKey Unit:=wdLine, Extend:=wdExtend If VBA.Len(Selection.Range.Text) = 0 Then With Application.Dialogs(wdDialogInsertPicture) Adg = .Show Ntemp = .Name End With End If If Adg <> -1 Then Exit Sub Narray = VBA.Split(Ntemp, "\", -1) Pname = VBA.Left(Narray(UBound(Narray)), VBA.Len(Narray(UBound(Narray))) - 4) Selection.MoveDown Unit:=wdLine, Count:=1 Addname = InputBox("请为插入的图片写上说明文字", "请输入", Pname) Selection.InsertAfter Addname YesorNoKK = False Application.ScreenUpdating = False End Sub
|