![Quote](https://www.excelforum.com/images/misc/quote_icon.png)
Originally Posted by
mc84excel
when I run your code on my test module, it removes the empty line between test and test2. How can I edit your code to stop it removing the gap between procedures?
I've tried
.InsertLines lngProcLine, strProcedure
and
.InsertLines lngStartLine + 1, strProcedure
- neither of these worked.
Private Sub CleanUpDeclarations()
'/ Puts variables at the start of a procedure (where they belong)
'/ Rory Archibalds MVP
Dim VBProj As Object
Dim VBComp As Object
Dim VBCodeMod As Object
Dim strProcName As String
Dim strThisModule As String
Dim strProcedure As String
Dim strModName As String
Dim ProcKind As Long
Dim lngModLineNo As Long
Dim lngStartLine As Long
Dim lngProcLine As Long
Dim lngNumLines As Long
'get name of this module - we dont want to check this
strThisModule = Application.VBE.ActiveCodePane.CodeModule
Set VBProj = ThisWorkbook.VBProject
For Each VBComp In VBProj.VBComponents
strModName = VBComp.Name
If strModName <> strThisModule Then
'Scan through the code module, looking for procedures
With VBProj.VBComponents(strModName).CodeModule
If .CountOfDeclarationLines > 0 Then
lngModLineNo = .CountOfDeclarationLines
Else
lngModLineNo = 1
End If
Do While lngModLineNo < .CountOfLines
strProcName = .ProcOfLine(lngModLineNo, ProcKind)
If Len(strProcName) > 0 Then
lngStartLine = .ProcStartLine(strProcName, ProcKind)
lngProcLine = .ProcBodyLine(strProcName, ProcKind)
lngNumLines = .ProcCountLines(strProcName, ProcKind)
strProcedure = fnstrSortProc(.Lines(lngProcLine, lngNumLines))
.DeleteLines lngProcLine, (lngNumLines + lngStartLine - lngProcLine)
.InsertLines lngStartLine, strProcedure
lngModLineNo = lngModLineNo + .ProcCountLines(strProcName, ProcKind)
Else
lngModLineNo = lngModLineNo + 1
End If
Loop
End With
End If
Next VBComp
End Sub
Private Function fnstrSortProc(strProcedure As String) As String
Dim astrLines() As String
Dim n As Long
Dim strLine As String
Dim strDec As String
Dim strOut As String
Dim blnStarted As Boolean
astrLines = Split(strProcedure, vbCrLf)
For n = LBound(astrLines) + 1 To UBound(astrLines)
strLine = Trim$(astrLines(n))
If Left$(LCase$(strLine), 4) = "dim " Or Left$(LCase$(strLine), 6) = "const " Then
blnStarted = True
strDec = strDec & vbCrLf & vbTab & strLine
Else
If Not blnStarted Then
If Left$(strLine, 1) <> "'" _
And Left$(LCase$(strLine), 4) <> "rem " _
And LenB(strLine) <> 0 Then
blnStarted = True
End If
End If
If blnStarted Then
strOut = strOut & vbCrLf & astrLines(n)
Else
strDec = strDec & vbCrLf & astrLines(n)
End If
End If
Next n
fnstrSortProc = vbCrLf & astrLines(LBound(astrLines)) & strDec & vbCrLf & strOut
End Function
Bookmarks