-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVBA_stacktherows
More file actions
117 lines (94 loc) · 3.11 KB
/
VBA_stacktherows
File metadata and controls
117 lines (94 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
Option Explicit
Public Sub ColumnA_TransposeAndSplitToColumnC()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
If lastRow < 1 Then
MsgBox "Column A appears empty.", vbExclamation
Exit Sub
End If
Dim sep As String
sep = CStr(Application.InputBox( _
Prompt:="Enter separator to join values:", _
Title:="Separator", Type:=2))
If sep = "False" Then Exit Sub
Dim maxLen As Long
Dim vMax As Variant
vMax = Application.InputBox( _
Prompt:="Enter max length per output cell (max 32767):", _
Title:="Max Cell Length", Type:=1)
If vMax = False Then Exit Sub
maxLen = CLng(vMax)
If maxLen <= 0 Then
MsgBox "Max length must be greater than 0.", vbExclamation
Exit Sub
End If
If maxLen > 32767 Then maxLen = 32767
Dim joined As String
Dim r As Long
Dim cellValue As String
joined = ""
For r = 1 To lastRow
cellValue = Trim$(CStr(ws.Cells(r, "A").Value))
If Len(cellValue) > 0 Then
If Len(joined) = 0 Then
joined = cellValue
Else
joined = joined & sep & cellValue
End If
End If
Next r
If Len(joined) = 0 Then
MsgBox "No non-empty values found in Column A.", vbExclamation
Exit Sub
End If
ws.Range("C:C").ClearContents
WriteChunksToColumn ws, joined, sep, maxLen, 1, "C"
MsgBox "Done. Wrote split output to Column C.", vbInformation
End Sub
Private Sub WriteChunksToColumn(ByVal ws As Worksheet, _
ByVal bigText As String, _
ByVal sep As String, _
ByVal maxLen As Long, _
ByVal startRow As Long, _
ByVal colLetter As String)
Dim rowOut As Long
rowOut = startRow
Dim remaining As String
remaining = bigText
Do While Len(remaining) > 0
Dim chunk As String
chunk = NextChunk(remaining, sep, maxLen)
ws.Cells(rowOut, colLetter).Value = chunk
rowOut = rowOut + 1
remaining = Mid$(remaining, Len(chunk) + 1)
If Len(sep) > 0 Then
If Left$(remaining, Len(sep)) = sep Then
remaining = Mid$(remaining, Len(sep) + 1)
End If
End If
Loop
End Sub
Private Function NextChunk(ByVal s As String, ByVal sep As String, ByVal maxLen As Long) As String
If Len(s) <= maxLen Then
NextChunk = s
Exit Function
End If
If Len(sep) = 0 Then
NextChunk = Left$(s, maxLen)
Exit Function
End If
Dim candidate As String
candidate = Left$(s, maxLen)
Dim pos As Long
pos = InStrRev(candidate, sep)
If pos > 0 Then
NextChunk = Left$(candidate, pos - 1)
If Len(NextChunk) = 0 Then
NextChunk = Left$(s, maxLen)
End If
Else
NextChunk = Left$(s, maxLen)
End If
End Function