Convert Array to String in Excel - excel-formula

I am trying to convert an array output to string for later manipulation and visibility.
For example I have an array {681120;953160;909420;16300}.
How would I go about converting that into a string?

Try:
Option Explicit
Sub ArrayLoop()
Dim ArrList As Variant
Dim ArrItem As Variant
Dim Result As String
ArrList = Array("681120", "953160", "909420", "16300")
Result = ""
For Each ArrItem In ArrList
If Result = "" Then
Result = ArrItem
Else: Result = Result & "_" & ArrItem
End If
Next
End Sub

Related

How convert sentences to column/row of single words

Why is it not working?
Prints only the first word and I don't know how I can change "10" in "For" on something like "For each word in sentence"
Sub Change()
Dim S As String
Dim i As Integer
Dim x As String
S = InputBox("Sentence")
x = Split(S, " ")
For i = 1 To x
Cells(1, i).Value = Split(S, " ")
Next i
End Sub
Try this:
Public Sub Change()
Dim sentence As String: sentence = InputBox("Sentence")
Dim col As Long: col = 1
Dim word As Variant: For Each word In Split(sentence, " ")
ThisWorkbook.Worksheets("Sheet1").Cells(1, col).Value = word
col = col + 1
Next
End Sub
Split Sentence to Worksheet
Option Explicit
Sub SentenceToRow()
Const ProcTitle As String = "Sentence to Row"
Const First As String = "A1"
Dim S As Variant: S = InputBox("Input a Sentence", ProcTitle)
If Len(S) = 0 Then
MsgBox "You canceled.", vbExclamation, ProcTitle
Exit Sub
End If
Dim Strings() As String: Strings = Split(S)
Dim cCount As Long: cCount = UBound(Strings) + 1
Dim ws As Worksheet: Set ws = ActiveSheet
Dim rg As Range: Set rg = ws.Range(First).Resize(, cCount)
rg.Value = Strings
MsgBox "Sentence split to a row.", vbInformation, ProcTitle
End Sub
Sub SentenceToColumn()
Const ProcTitle As String = "Sentence to Column"
Const First As String = "A1"
Dim S As Variant: S = InputBox("Input a Sentence", ProcTitle)
If Len(S) = 0 Then
MsgBox "You canceled.", vbExclamation, ProcTitle
Exit Sub
End If
Dim Strings() As String: Strings = Split(S)
Dim rCount As Long: rCount = UBound(Strings) + 1
Dim ws As Worksheet: Set ws = ActiveSheet
Dim rg As Range: Set rg = ws.Range(First).Resize(rCount)
rg.Value = Application.Transpose(Strings)
MsgBox "Sentence split to a column.", vbInformation, ProcTitle
End Sub
this is fast and eficient:
Sub testSplit2Row()
Dim frase As String
frase = "las palabras de amor"
Dim ary As Variant
ary = Split(frase, " ")
Dim dest As Range
Dim start As Range
Set start = Range("B1")
Set dest = start.Resize(UBound(ary) + 1)
dest.Value = Application.Transpose(ary)
start.Resize(, UBound(ary) + 1).Value = ary
End Sub
If you dispose of the dynamic array functions of MSExcel 365, you might profit from the following function, usable as well as udf or via code.
The function words() accepts range values, array values or explicit string inputs as first argument s; the second argument IsVertical is optional and indicates that results will be returned as vertical array by default (instead of a "flat" array).
Public Function words(ByVal s As Variant, Optional IsVertical As Boolean = True)
'Debug.Print VarType(s)
If VarType(s) >= vbArray Then
s = Replace(Application.WorksheetFunction.ArrayToText(s), ",", "")
End If
words = Split(s)
If IsVertical Then
words = Application.WorksheetFunction.Transpose(Split(s))
End If
End Function
a) Example using a multi-row range input in B2
=words(A2:A4)
b) Example call via code
Option Explicit ' module head of code module
Sub ExampleCall
With Sheet1
Dim wds As Variant
wds = words(.Range("A2:A4"))
.Range("A10").Resize(UBound(wds), UBound(wds, 2)) = wds
End With
End Sub
If you intend, however to display results horizontally, just code as follows (note the dimension change!):
'...
wds = words(.Range("a2:a4"), False) ' False returns "flat" 1-dim array
.Range("A10").Resize(1, UBound(wds)) = wds

Why is my User defined Function not showing results VBA

I have created a UDF called YRatio(Str). When I use the insert formula for a cell the result appears on the dialog box but inside the cell it shows "=YRatio(C2)"
The result I get is right. But it doesn't appear in the cells.
Function YRatio(CellRef As String) As String
Dim Arr() As String
Dim tot As Integer
Dim yyes As Integer
Dim Str As String
Str = CellRef '.Value
Arr() = Split(Str, Chr(10))
For Each Line In Arr
tot = tot + 1
If Left(Line, 1) = "Y" Then
yyes = yyes + 1
End If
Next
YRatio = CStr(yyes) & "/" & CStr(tot)
End Function
inside the cell it shows "=YRatio(C2)"
You need to change the formatting of the cell to General. Currently it is formatted as Text
Also Arr() = Split(Str, Chr(10)) in your code should be Arr() = Split(Range(Str).Value, Chr(10)).
Imp Tip: Avoid using LINE and STR as variables. Use more meaningful names.
Your code can be written as
Option Explicit
Function YRatio(CellRef As Range) As String
Dim Arr() As String
Dim tot As Long
Dim yyes As Long
Dim itm As Variant
Arr() = Split(CellRef.Value2, Chr(10))
For Each itm In Arr
tot = tot + 1
If Left(itm, 1) = "Y" Then yyes = yyes + 1
Next
YRatio = yyes & "/" & tot
End Function
Here I am passing the cell as Range.
Now you can type in the cell =YRatio(C2) which is formatted as General and it will work.
You can use use this version of the code which uses UBound(Arr) to get the total elements of the array rather then using tot = tot + 1
Option Explicit
Function YRatio(CellRef As Range) As String
Dim Arr() As String
Dim yyes As Long
Dim itm As Variant
Arr() = Split(CellRef.Value2, Chr(10))
For Each itm In Arr
If Left(itm, 1) = "Y" Then yyes = yyes + 1
Next
YRatio = yyes & "/" & UBound(Arr)
End Function

VB How can I use commas within an excel cell?

I want to use commas within an excel cell whilst keeping commas as the delimiter.
Sub
Dim countStations As Integer
Dim stationI
Dim rawFileArray() As String = File.ReadAllLines(rawFileName)
For Each station In stationsNameList
stationI = stationList(countStations)
For i As Integer = 0 To rawFileArray.Count - 1
If rawFileArray(i).IndexOf(station, 0) <> -1 Then
stationI.rawData += rawFileArray(i) & "," & stationI.stationName & "," & stationI.region & vbNewLine
End If
Next
CreateStationsXLSX(station, countStations)
countStations += 1
Next
End Sub
Sub (ByRef station As String, ByRef countStations As Integer)
Dim fi = New FileInfo("FQR Generator Data\Stations\" & station & ".xlsx")
Using p As New ExcelPackage(fi)
Dim wsQuantity = p.Workbook.Worksheets.Add("Quantity Summary")
Dim wsQuality = p.Workbook.Worksheets.Add("Quality Summary")
Dim wsRaw = p.Workbook.Worksheets.Add("Raw")
Dim wsStation = p.Workbook.Worksheets.Add(station)
Dim currentCell As Integer = 0
Dim stationToLoad As String = stationList(countStations).rawData
'Importing Raw Data into worksheet
wsRaw.Cells("A1").LoadFromText(stationsHeader)
wsRaw.Cells("A2").LoadFromText(stationToLoad)
p.Save()
End Using
'GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FQR Generator Data\Stations\", station
End Sub
Here is what is entered into excel ...
Actual Output
Here is what is i want entered into excel...
Wanted Output
Don't use LoadFromText, use Value:
wsRaw.Cells("A2").Value = "this,with,commas"

Concatenate if, in a range

I'm having a issue to get a text result which is a concatenate/join of "X" cells of a column based quantity in another cell. Example:
Cell value = 2
Name
Txt1
Txt2
Txt3
Txt4
Result = Txt1Txt2
Cell value = 3
Name
Txt1
Txt2
Txt3
Txt4
Result = Txt1Txt2Txt3
One must have CONCAT():
=CONCAT(A2:INDEX(A2:A5,C1))
If one does not have CONCAT this UDF will mimic the function. Put this in a module attached to the workbook:
Function CONCAT(rng As Range)
Dim rngArr As Variant
rngArr = rng
On Error GoTo onlyone
Dim itm As Variant
For Each itm In rngArr
CONCAT = CONCAT & itm
Next itm
Exit Function
onlyone:
CONCAT = rngArr
End Function

VBA Loop that removes punctuation from a given range

I am pretty new to VBA, and i need to make a loop that removes certain punctuation which is referenced as values A2:A33 on my spreadsheet, from a string. This is what I have so far, struggling with the replace function. Any help would be greatly appreciated thanks!
Function CleanDescription(rawDescription As String) As String
Dim punctuationRng As Range
Set punctuationRng = Worksheets("ToRemove").Range("A2:A33")
Dim cleanDesc As String
cleanDesc = rawDescription
For i = 1 To punctuationRng.Count
cleanDesc = Replace(cleanDesc, punctuationRng, "")
Next i
CleanDescription = cleanDesc
End Function
You can achieve substituting each value in a range of cells that is present in a string by a For Each:
Function CleanDescription(rawDescription As String) As String
Dim punctuationRng As Range
Set punctuationRng = Worksheets("ToRemove").Range("A2:A33")
Dim cleanDesc As String
cleanDesc = rawDescription
For Each punctuationCell In punctuationRng
cleanDesc = Replace(cleanDesc, punctuationCell.Value, "")
Next punctuationCell
CleanDescription = cleanDesc
End Function
If you don't like the For Each you could also achieve it with a For Loop:
Dim cellValue As String
For r = 1 to punctuationRng.Rows.Count
For c = 1 to punctuationRng.Columns.Count
cellValue = punctuationRng.cells(r, c).Value
cleanDesc = Replace(cleanDesc, cellValue, "")
Next c
Next r
You can use a For Each Loop as shown below
Function CleanDescription(rawDescription As String) As String
Dim punctuationRng As Range
Set punctuationRng = Worksheets("ToRemove").Range("A2:A33")
Dim cleanDesc As String
cleanDesc = rawDescription
Dim aCell As Range
For Each aCell In punctuationRng
cleanDesc = Replace(cleanDesc, aCell.Value2, "")
Next aCell
CleanDescription = cleanDesc
End Function

Resources