VBA removes slashes - excel

I am new to VBA in excel. So, i create a string from multiple parts and output it in a cell on some sheet like this:
Sheets("Output").Cells(iRow, 1).Value = LArray(0) + "?" + adding + "/#" + LArrayNew(1)
I am expecting: text?text/#text
But result on excel sheet is: text?text#text
Where is the "/"?

Something like:
Sub dural()
Dim LArray(0 To 1) As String
Dim adding As String, LArrayNew(0 To 1) As String
adding = "X"
LArrayNew(1) = "New"
LArray(0) = "0"
iRow = 1
Sheets("Output").Cells(iRow, 1).Value = LArray(0) & "?" & adding & "/#" & LArrayNew(1)
End Sub
will produce:
0?X/#New
Note the slash is there!

Related

Combining consecutive numbers_Excel Formula or VBA

I need to find away to be able to combine consecutive numbers. It could be either by formula or VBA code, but I honestly don't know where to start and I could not find anything similar posted that I could use for my case.
Ex:
This:
9630184784, 9630184786, 9630184787, 9630184788, 9630184814, 9630184815, 9630184816, 9630184817
To:
9630184784, 9630184786-9630184788, 9630184814-9630184817
Thanks in advance!
Hyra
=MID(CONCAT(IFERROR(CHOOSE(MMULT(COUNTIF(A:A,A$1:A$8+{1,-1}),{1;3}/2)+1,",","-")&A1:A8,"")),2,99)
#Excel 2019
=MID(CONCAT(IFERROR(CHOOSE(MMULT(COUNTIF(A1,"*"&FILTERXML("<a><b>"&SUBSTITUTE(A1,","," </b><b>")&"</b></a>","a/b")+{1,-1}&"*"),{1;3}/2)+1,",","-")&FILTERXML("<a><b>"&SUBSTITUTE(A1,","," </b><b>")&"</b></a>","a/b"),"")),2,99)
#Excel 365
=LET(x,FILTERXML("<a><b>"&SUBSTITUTE(A1,","," </b><b>")&"</b></a>","a/b"),MID(CONCAT(IFERROR(CHOOSE(MMULT(COUNTIF(A1,"*"&x+{1,-1}&"*"),{1;3}/2)+1,",","-")&x,"")),2,99))
Answer change from 象山海鲜.
This VBA function worked fine for me. It was posted by mikerickson at mrexcel.
https://www.mrexcel.com/board/threads/convert-list-of-sequential-numbers-into-ranges.978486/
Function IntoRanges(aString As String, Optional Delimiter As String = ",") As String
Dim NextBit As String
Dim i As Long
Dim Items As Variant
Items = Split(aString, Delimiter)
IntoRanges = Items(0)
For i = 0 To UBound(Items) - 1
If Val(Items(i)) + 1 = Val(Items(i + 1)) Then
NextBit = "-" & Val(Items(i + 1))
Else
If NextBit = vbNullString Then
IntoRanges = IntoRanges & Delimiter & Val(Items(i + 1))
Else
IntoRanges = IntoRanges & NextBit & Delimiter & Val(Items(i + 1))
NextBit = vbNullString
End If
End If
Next i
IntoRanges = IntoRanges & NextBit
End Function

VBA code to auto serial number in column A when data entered in the userform

I have a userform in which user can fill the data and data will insert in column C to Z. I need a code, either in worksheet or in userform to auto fill serial number starting with BA00860 which will fill in column A everytime data has enter.
I tried with the below Code under the Commandbutton_Click I was able to generate Serial numbers from BA00860 to BA00869, then after it is starting with BA01861 but not BA00870. Please correct my code as I required to be BA00860 … BA00870 … BA00880 and so on.
Me.txtId.Value = "BA" & Format(Application.Max(Sheets("Tasks").Range("A12:A65536")) + 1, "00860")
ActiveCell.Offset(0, 0).Value = Me.txtId.Value
ActiveCell.Offset(0, 0).NumberFormat = "00860"
Note that this .NumberFormat = "00860" is no valid number format.
You can do this easily with a formula. Assume your first serial number is written in A1 like …
Then you can just use the formula =LEFT(A1,2) & TEXT(RIGHT(A1,5)+1,"00000") in cell A2 and copy it down to get the following:
In VBA you could use something like
Dim LastSN As String
LastSN = Range("A1").Value 'eg BA00860
Dim NextSN As String
NextSN = Left$(LastSN, 2) & Format$(Right(LastSN, 5) + 1, "00000")
Full example according comments:
Sub Test()
Dim LastSN As String
LastSN = "BA00860"
Dim NextSN As String
NextSN = Left$(LastSN, 2) & Format$(Right(LastSN, 5) + 1, "00000")
MsgBox "LastSN was: " & LastSN & vbCrLf & "NextSN is: " & NextSN
End Sub

Adding freshly created formula into new module

I've just created a brand new macro. Took function down below from internet (all credits goes to trumpexcel.com), code down below
Function CONCATENATEMULTIPLE(Ref As Range, Separator As String) As String
Dim Cell As Range
Dim Result As String
For Each Cell In Ref
Result = Result & Cell.Value & Separator
Next Cell
CONCATENATEMULTIPLE = Left(Result, Len(Result) - 1)
End Function
Then I proceed to extract data from various columns and into the one (my table is 20 rows x 10 columns)
Sub conact_data()
Dim i As Integer
For i = 2 To Cells(Rows.Count, "A").End(xlUp).Row
Cells(i, "M").Value = Cells(i, "A").Value & " " & _
Cells(i, "B").Value & " / " & Cells(i, "D").Value & "; "
Next i
End Sub
Thanks to that I've got combined data from column A, B and D, so its 20 rows. All I want to do now is to concatenate data from M2:M21 using CONCATENATEMULTIPLE function therefore I try various approach (I want this huge line in P2 cell) like :
Cells(2, 16).Value = CONCATENATEMULTIPLE (M2:M21, " ")
or
Range("P2") = "CONCATENATEMULTIPLE (M2:M21, " ")"
I don't really know how to apply that
Secondly, I'd like withdraw the Cells(i, "B").Value as percentage. Can I do that in one line like Cells(i, "B").NumberFormat="0.00%".Value (which is not working for me obviously) else I need to copy column B into another column with number format and then combine the new column, properly formatted instead of column B?
Thanks in advance
Percent format: Range("B" & i).NumberFormat = "0.00%"
CONCATENATEMULTIPLE
In VBA, CHR(32) = " "
In Excel, CHAR(32) = " "
With that being said...
'Value
Range("P2").Value = CONCATENATEMULTIPLE(Range("M2:M21"), CHR(32))
'Formula
Range("P2").Formula = "=CONCATENATEMULTIPLE(M2:M21, CHAR(32))"
You should really qualify all of your ranges with a worksheet
Say your workbook has 10 sheets. When you say Range("P2"), how do we (VBE) know what sheet you mean? Objects need to be properly qualified. Sometimes this is not a huge issue, but when you are working across multiple sheets, not qualifying ranges can lead to some unexpected results.
You can qualify with a worksheet a few ways.
Directly: ThisWorkbook.Sheets("Sheet1").Range("P2").Copy
Or use a variable like so
Dim ws as Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("P2").Copy
Now there is no room for ambiguity (potential errors) as to the exact location of Range("P2")
First of all, remove your ConcatenateMultiple() code, and instead use Excel worksheet function CONCAT(), which takes a range and a delimiter as parameters.
Here is how you can handle the percentage issue and supply a default for non-numeric items. I've also cleaned up the way you reference your data range.
Sub concat_data()
Dim rngRow As Range, vResult As Variant
Const DEFAULT = 0 'Can also be set to a text value, eg. "Missing"
For Each rngRow In [A2].CurrentRegion.Rows
If IsNumeric(rngRow.Cells(, 4)) Then vResult = rngRow.Cells(, 4) * 100 & "%" Else vResult = DEFAULT
Range("M" & rngRow.Row) = rngRow.Cells(, 1) & rngRow.Cells(, 2) & "/" & vResult & ";"
Next
[M2].End(xlDown).Offset(1).Formula = "=CONCAT(M2:M" & [M2].End(xlDown).Row & ",TRUE,"" "")"
End Sub
I'm not a fan of hard-coding range references, like the [A2] or Range("M"), but will leave that for another time.

Create several line breaks in excel cell using Excel VBA

I will try to explain the issue as clear as possible.
I have a column in an Excel file and each cell in this column contains a description of some issue. The description has four levels such as Name, Issue, Solution and Result, all these four in the same cell.
I need VBA code that will find each level in each cell and create line break in the cell.
So instead of this:
Name: 123 Issue: My issue: Solution: Try to resolve Result: Resolved.
After the code runs will be like this:
Name: 123 (line break)
Issue: My issue (line break)
Solution: Try to resolve (line break)
Result: Resolved (line break)
Please let me know if there is any solution?
Select the cell containing the data and run:
Sub FixData()
Dim r As Range
Set r = ActiveCell
t = r.Text
t = Replace(t, "Issue:", Chr(10) & "Issue:")
t = Replace(t, "Solution:", Chr(10) & "Solution:")
t = Replace(t, "Result:", Chr(10) & "Result:")
r.Value = t
r.WrapText = True
End Sub
If necessary, you can put this in a loop.
loop through the cells and add linefeeds.
sub makelfs()
dim i as long, j as long, arr as variant, str as string
arr = array("Issue:","Solution:","Result:")
with worksheets("excel file")
for i=2 to .cells(.rows.count, "a column in excel file").end(xlup).row
str = .cells(i, "a column in excel file").value2
for j = lbound(arr) to ubound(arr)
str = replace(str, arr(j), vblf & arr(j))
next j
.cells(i, "a column in excel file") = str
.cells(i, "a column in excel file").wraptext = true
next i
end with
end sub
s = "Name: 123 Issue: My issue: Solution: Try to resolve Result: Resolved."
arr = Split(s, Chr(32))
For Each Item In arr
If cnt > 0 Then
If Right(Item, 1) = ":" Then Item = vbCrLf & Item
End If
output = output & Item & " "
cnt = cnt + 1
Next Item
Debug.Print output
Using a slightly different approach which doesn't rely on Issue, Solution and Result being present.
As said in my comment - look for the first space before the colon and replace it with a line feed (put vbcr in my comment - should be vblf).
Public Function AddLineBreak(Target As Range) As String
Dim lColon As Long
Dim lSpace As Long
Dim sFinal As String
sFinal = Target.Value
lSpace = Len(sFinal)
Do While lSpace <> 0
sFinal = Left(sFinal, lSpace - 1) & Replace(sFinal, " ", vbLf, lSpace, 1)
lColon = InStrRev(sFinal, ":", lSpace - 1)
lSpace = InStrRev(sFinal, " ", lColon)
Loop
AddLineBreak = Trim(sFinal)
End Function
You can call the function in a procedure:
Sub Test()
Dim rCell As Range
For Each rCell In Sheet1.Range("A1:A13")
rCell = AddLineBreak(rCell)
Next rCell
End Sub
or as a worksheet function:
=AddLineBreak(A1)
This assumes an error in the original string you posted:
Name: 123 Issue: My issue: Solution: Try to resolve Result: Resolved. should be
Name: 123 Issue: My issue Solution: Try to resolve Result: Resolved.
(extra colon before Solution which is not shown in your After code example).
Edit - it also means you cannot have spaces in your headings. So you can have " Issue:" or " My_Issue:" but not " My Issue:"

Cell reference based on FOR loop index

Here is some of my code:
Dim wbX As Workbook
Dim wbY As Workbook
Set wbX = Application.Workbooks.Open("C:\Converter\aaa.xls")
Set wbY = Application.Workbooks.Open("C:\Converter\bbb.xlsx")
For i = 1 To wbX.Sheets.Count
wbY.Sheets(1).Activate
Range("Y" & i + 2).Select
ActiveSheet.Range("Y" & i + 2).Formula = "=RIGHT(("S" & i + 2); 4)"
The problem is that ("S" & i + 2) is not recognized as a cell - VBA spits out syntax errors.
Your expression "Y" & i + 2 does not yield a valid cell reference because you concatenate a number to a string. You must convert the numeric expression to a string:
"Y" & Str(i + 2)
What I understand from your comment, the assignment should be written as:
"=LEFT(S" & Trim(Str(i + 2)) & "; 4)" ' yields e.g.: =LEFT(S3; 4)
(The LEFT function gets the first characters from a string. This assumes the cells you reference contains strings, or that VB converts the value to a string first. And here you must use Trim(Str(i + 2)) because you are constructing a string to place as a formula in the cell.)
Maybe this example helps you:
Option Explicit
Sub test()
Dim rngC As Range
For Each rngC In Range("C2:C100")
rngC.Offset(0, 4) = Right(rngC, 4)
Next
End Sub

Resources