Sub ClearOutside_v4()
Dim rFound As Range, cRange As Range
Dim i As Long, j As Long, k As Long, w As Long, h As Long, lc As Long, rc As Long, tr As Long, br As Long
Application.ScreenUpdating = False
With Sheets("PNG").UsedRange
For i = 1 To 4
If i < 3 Then
Set rFound = .Find(What:=255, LookAt:=xlWhole, SearchOrder:=xlByColumns)
lc = rFound.Column
j = 1
Do Until rFound.Offset(j).Value <> 255
j = j + 1
Loop
With .Rows(rFound.Row + j / 2)
rc = .Find(What:=255, After:=.Cells(lc + 1), LookAt:=xlWhole).Column
If .Cells(rc + 1).Value = 255 Then rc = rc + 1
w = rc - lc + 1
k = 0
Do Until .Cells(rc + k) <> 255 Or rc + k = .Cells.Count
k = k + 1
Loop
rc = rc + k
If .Columns.Count - rc < w Then rc = .Columns.Count
k = 0
Do Until IsEmpty(.Cells(lc - k).Value) Or lc - k = 1
k = k + 1
Loop
lc = lc - k
End With
With .Columns(lc + (rc - lc) / 2)
tr = .Find(What:=255, After:=.Cells(rFound.Row + j / 2), LookAt:=xlWhole, SearchDirection:=xlPrevious).Row
If .Cells(tr - 1).Value = 255 Then tr = tr - 1
br = .Find(What:=255, After:=.Cells(rFound.Row + j / 2), LookAt:=xlWhole, SearchDirection:=xlNext).Row
If .Cells(br + 1).Value = 255 Then br = br + 1
h = br - tr + 1
k = 0
Do Until .Cells(br + k) <> 255 Or br + k = .Cells.Count
k = k + 1
Loop
br = br + k
If .Rows.Count - br < h Then br = .Rows.Count
k = 0
Do Until IsEmpty(.Cells(tr - k).Value) Or tr - k = 1
k = k + 1
Loop
tr = tr - k
End With
Else
If i = 3 Then Set rFound = .Find(What:=255, LookAt:=xlWhole, SearchOrder:=xlByRows)
If i = 3 Then
lc = .Rows(1).SpecialCells(xlConstants).Cells(1).Column
Else
lc = .SpecialCells(xlCellTypeLastCell).CurrentRegion.Column
End If
rc = .Columns.Count
tr = IIf(i = 3, 1, rFound.Row + h + 1)
br = IIf(i = 3, rFound.Row + h + 1, .Rows.Count)
End If
Set cRange = .Range(.Cells(tr, lc), .Cells(br, rc))
ClearCircle cRange
Next i
End With
Application.ScreenUpdating = True
End Sub
Sub ClearCircle(rng As Range)
Dim PNG As Worksheet, TIFF As Worksheet
Dim rCol As Range, rngFound As Range
Set PNG = Sheets("PNG")
Set TIFF = Sheets("TIFF")
For Each rCol In rng.Columns
With rCol
Set rngFound = Nothing
Set rngFound = .Find(What:=255, After:=.Cells(.Rows.Count), LookAt:=xlWhole, SearchDirection:=xlNext)
If rngFound Is Nothing Then
rCol.ClearContents
TIFF.Range(rCol.Address).ClearContents
Else
If rngFound.Row > .Row Then
.Cells(1).Resize(rngFound.Offset(-1).Row - .Row + 1).ClearContents
TIFF.Range(.Cells(1).Address, rngFound.Offset(-1).Address).ClearContents
End If
Set rngFound = .Find(What:=255, After:=.Cells(1), LookAt:=xlWhole, SearchDirection:=xlPrevious)
If rngFound.Row < .Cells(.Rows.Count).Row Then
.Cells(rngFound.Row - .Row + 1).Resize(.Row + .Rows.Count - rngFound.Row).ClearContents
TIFF.Range(rngFound.Offset(1).Address, .Cells(.Rows.Count).Address).ClearContents
End If
End If
End With
Next rCol
rng.Replace What:=255, Replacement:="", LookAt:=xlWhole
TIFF.Range(rng.Address).Replace What:=255, Replacement:="", LookAt:=xlWhole
End Sub