【发布时间】:2016-08-20 14:50:21
【问题描述】:
我需要一些帮助来缩短这段代码。
我需要将此代码 If (linha >= 20 And linha <= 21) 用于 50 行 (linha) 间隔
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim foto As Range
Dim destino As Range
Dim linha As Long
Dim fName As String
Dim pName As String
Dim iName As String
Dim iNameClean As String
Dim iNameExcel As String
Dim fNameExcel As String
Set foto = Target.Cells(1)
Set destino = Me.Range("AU:BC,BN:BV,CG:CO,CZ:DH,DS:EA,EL:ET,FE:FM,FX:GF,GQ:GY,HJ:HR,IC:IK,IV:JD,JO:JW,KH:KP,NF:NN,NY:OG,OR:OZ,PK:PS")
If Not Application.Intersect(foto, destino) Is Nothing Then
linha = foto.Row
If (linha >= 20 And linha <= 21) Then
With ActiveSheet
fName = Application.GetOpenFilename("Picture files (*.jpg;*.gif;*.bmp;*.tif), *.jpgs;*.gif;*.bmp;*.tif", , _
"Select picture to insert")
iName = Dir("" & fName & "")
If fName = "False" Then Exit Sub
iNameClean = Left(iName, Len(iName) - 4)
iNameExcel = "+Info"
fNameExcel = "F:\path\EXCEL\" & foto.Offset(1, 3).Value & ".xlsx"
With ActiveSheet
.Unprotect Password:="1234"
ActiveSheet.Pictures.Insert(fName).Select
foto.Offset(0, 2).Formula = "=HYPERLINK(""" & fName & """,""" & iNameClean & """)"
foto.Offset(0, 2).Font.ColorIndex = 1 ' preto
foto.Offset(0, 2).Font.Size = 9
foto.Offset(0, 2).Font.Underline = False
foto.Offset(0, 3).Formula = "=HYPERLINK(""" & fNameExcel & """,""" & iNameExcel & """)"
foto.Offset(0, 3).Font.ColorIndex = 1 ' preto
foto.Offset(0, 3).Font.Size = 9
foto.Offset(0, 3).Font.Underline = False
With Selection.ShapeRange
.LockAspectRatio = msoFalse
.Height = ActiveCell.MergeArea.Height
.Width = ActiveCell.MergeArea.Width
.Top = ActiveCell.Top
.Left = ActiveCell.Left
End With
.Protect Password:="1234"
End With
End With
End If
End Sub
【问题讨论】:
-
如果你可以edit标题简洁地解释代码的作用,并在问题正文中扩展一些周围的上下文,这将是一个完美的问题为Code Review。就目前而言,对于 Stack Overflow 来说,这个问题有点太宽泛了。
-
为什么需要缩短代码?如果您收到错误“程序太大”,那么只需将其分解为几个程序即可。如果超出模块大小,则将您的代码分布在多个模块中。
-
@Ralph 如果你得到“程序太大”的错误,你有更大的问题,需要阅读一下SRP ;-)
-
@Ralph 它很可能适用于此。假设
If块的内容可以划分为另一个接受一些参数的子/函数。 -
哦等等,是不是
If linha >= x And linha <= y Then块复制+粘贴了这么多次程序长度居然超出了限制?如果是这样,那么是的@Ralph 的链接有你的答案,你的问题有点不清楚。也就是说,如果您正在寻求帮助,将其分解成更易于管理的部分并使其更高效,Code Review 仍然是您的理想去处。