Advertisement
UEZ

VBA gedöns (Excel Cell Content Swap)

UEZ
Apr 25th, 2014
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.29 KB | None | 0 0
  1. 'coded by v2.01 UEZ build 2014-05-26
  2. Sub Swap_Coordinate2()
  3.     Dim Cells As Range
  4.     Dim Result As Variant
  5.     For Each Cells In Application.selection
  6.         If Cells.Value <> "" Then
  7.             Result = SwapIt(Cells.Value, Cells.Row, Cells.Column)
  8.             If Result <> "" Then
  9.                 'MsgBox ("*" & Result & "*")
  10.                 Cells.Value = Result
  11.             End If
  12.         End If
  13.     Next Cells
  14.     Set Cells = Nothing
  15. End Sub
  16.  
  17.  
  18. Function SwapIt(sString As String, iRow As Integer, iCol As Integer) As Variant
  19.     Dim RegEx As Object
  20.     Dim oResult As Object
  21.     Dim tokens As Variant
  22.     Dim sSwapped As Variant
  23.    
  24.     Set RegEx = CreateObject("VBScript.RegExp")
  25.     RegEx.Pattern = "(.+)\S"
  26.     RegEx.Global = True
  27.     RegEx.IgnoreCase = True
  28.     RegEx.MultiLine = True
  29.    
  30.     Set oResult = RegEx.Execute(sString)
  31.          
  32.     For Each tokens In oResult
  33.         sSwapped = sSwapped & RegExSwap(tokens.Value, iRow, iCol) & vbCrLf
  34.     Next
  35.     If sSwapped <> "" Then
  36.         SwapIt = Left(sSwapped, Len(sSwapped) - 2)
  37.     Else
  38.         MsgBox ("Error: unable to swap coordinates at " & iRow & ":" & iCol & " (x:y)! Please swap coordinates manually if applicable!")
  39.     End If
  40.     Set RegEx = Nothing
  41.     Set oResult = Nothing
  42. End Function
  43.  
  44.  
  45. Function RegExSwap(sText As Variant, iY As Integer, iX As Integer) As Variant
  46.  
  47.     Dim RegExResult As String
  48.     Dim allMatches As Object
  49.     Dim RegEx As Object
  50.     Set RegEx = CreateObject("VBScript.RegExp")
  51.    
  52.     RegEx.Pattern = "(.+) to (.+) (free.*)"
  53.     RegEx.Global = True
  54.     RegEx.IgnoreCase = True
  55.     Set allMatches = RegEx.Execute(sText)
  56.  
  57.     Select Case allMatches.Count
  58.         Case 1
  59.             RegExResult = allMatches.Item(0).SubMatches.Item(1) & " to " & allMatches.Item(0).SubMatches.Item(0) & " " & allMatches.Item(0).SubMatches.Item(2)
  60.         Case Else
  61.             RegEx.Pattern = "(.+) to (.+)"
  62.             Set allMatches = RegEx.Execute(sText)
  63.             If allMatches.Count = 1 Then
  64.                 RegExResult = allMatches.Item(0).SubMatches.Item(1) & " to " & allMatches.Item(0).SubMatches.Item(0)
  65.             Else
  66.                 RegExResult = sText
  67.             End If
  68.     End Select
  69.  
  70.     Set allMatches = Nothing
  71.     Set RegEx = Nothing
  72.     RegExSwap = RegExResult
  73. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement