I have the below VBA code and A and B are holding some strings. I want to concatenate these values with some other strings and store the result in a different cell, but I want only the strings in A and B to be formatted as bold and the rest as normal text.
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
' E.g.: A="currency", B="Small Int"
Worksheets("TestCases").Cells(i, 2) = "Verify the column " & A & " has same Data type " & B & " in code as well as Requirement document"
Expected output:
Verify the column currency has same Data type Small Int in code as well as Requirement document
Note: The values of A and B keep changing, so we cannot use the Characters() function.
Any help will be highly appreciated.
You can use the Characters() method - you just need to keep track of the length of the substrings. Personally, I would store the static strings in variables so that I can change them later without having to recalculate the indexes by hand:
' Untested
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
Dim S1 = "Verify the column "
Dim S2 = " has same Data type "
Dim S3 = " in code as well as Requirement document"
With Worksheets("TestCases").Cells(i, 2)
.Value = S1 & A & S2 & B & S3
.Characters(Len(S1), Len(A)).Font.Bold
.Characters(Len(S1)+Len(A)+Len(S2), Len(B)).Font.Bold
End With
The function to change the font style is:
[Cells/Cell range].Font.FontStyle = "Bold"
Therefore something like might work:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.FontStyle = "Bold"
You can also make things have underlines, strikethroughs etc... I found this really helpful blog post which goes through everything you should need to know:
http://software-solutions-online.com/excel-vba-formating-cells-and-ranges/#Jump4
I think you should have searched for this information yourself... Nevertheless this is the code that you should use to convert some cell data to bold:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.Bold = True
Related
I am trying to dynamically construct a formula based on an array that I have generated from a cell (separated by commas), as there is a varying amount of elements in the array I need to append a new "formula block" with the updated element to use in a if statement that is generated after the for each loop. VBA is throwing a type mismatch error in the InvestigateFormula = line, here is my code:
For Each Type In ToIgnore()
InvestigateFormula = "(ISNUMBER(SEARCH(*" & ToIgnore(Type) & "*," & _
AssetTypesCol & "2)),"
FullFormula = InvestigateFormula & FullFormula
Next Asset
FinalInvestigateFormula = "=IF(OR" & FullFormula & "),""Ignore"", """")"
ActiveCell.Formula = FinalInvestigateFormula
Please let me know if there is an easier way of doing this or how I might be able to correct the above code. Btw I am not declaring a variant I am simply declaring ToIgnore() as String and using the split function from the variable which contains the comma separated values to generate the array/items to loop over.
"Type" is a reserved name? Try strType instead?
I have a machine generated chat data exported to excel as below
User: I need help in cancelling my order
Agent: Sure I can assist you on that
User: cool
User: Also, I need your support in ordering some other item
User: I don't know how to do that
Agent: Sure, I'll help with all your queries
I'm trying to extract only the user text from the above conversation from each cell into a seperate cell in excel
I tried all known methods to the best of my knowledge to get it. Unfortunately, unable to do so. Please help me achieving this.
Sample output:
I want to extract only user typed message to a different cell from the above conversation like below
User: I need help in cancelling my order
User: cool
User: Also, I need your support in ordering some other item
User: I don't know how to do that
If VBA UDF is an option then we can use regular expressions like ...
Option Explicit
Function ExtractUserChat(ChatString As String) As String
Dim regex As Object, mc As Object, result As String, i As Long
Set regex = CreateObject("VBScript.regexp")
regex.ignorecase = False
regex.Global = True
regex.Pattern = "User: "
ChatString = regex.Replace(ChatString, "{<<USER>>: ")
'Or if you want each submatch on next line then
'ChatString = regex.Replace(ChatString, "{" & Chr(10) & "USER>>: ")
regex.Pattern = "Agent: "
ChatString = regex.Replace(ChatString, "}Agent: ") & "}"
regex.Pattern = "\{[^}]+\}"
Set mc = regex.Execute(ChatString)
result = ""
For i = 0 To mc.Count - 1
result = result & mc(i)
Next i
result = Replace(Replace(result, "{", ""), "}", "")
ExtractUserChat = result
End Function
Assuming the text string appears in a single cell, then FILTERXML might help (see here, for example).
I was able to get the desired result by using FILTERXML together with the the LET function:
=IFERROR(LET(
X, FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s"),
Y, IFERROR(SEARCH("Agent:", X)-2, LEN(X)),
"User: "&LEFT(X,Y)),
"")
Working step-by-step:
FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s")creates a dynamic array of the string, splitting the text into different rows whenever "User:" appears in the string.
Where X represents the value of each cell in the dynamic array generated in step 1, IFERROR(SEARCH("Agent:", X)-2, LEN(X)) returns either the position of the string "Agent:" within X or the length of X.
Using the LET function, we call step 1 X and step 2 Y. Then our output is the left-most Y characters of X, prepended with the string "User: " (to account for its removal in step 1).
We wrap the entire function in an IFERROR to maintain best practice .
Note that if you want the output in a single cell rather than multiple, you can simply join the cells together with TEXTJOIN. Something like the below would do the trick.
=TEXTJOIN(" ", 1, IFERROR(LET(
X, FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s"),
Y, IFERROR(SEARCH("Agent:", X)-2, LEN(X)),
"User: "&LEFT(X,Y)),
""))
At work I am required to reformat incorrect Addresses on a weekly basis from records in our Salesforce instance. We gather the incorrectly formatted addresses using a Report and export them to an Excel file. My job is simply to manipulate the data in the file to format them properly then reinsert them into the database.
Typically the addresses are formatted as so:
5 Sesame Street, Anytown, Anyplace
Separating these can be done easily by hand, but I typically have to work with hundreds of addresses at a time, and using default excel formulas tends to require lots of wrangling multiple cells at once to break it up into fragments.
Thus I wrote a custom formula to run through the cell and return a specific fragment of the string based on the "Comma Number" given. So if I give a Comma Number of 1, I would get "5 Sesame Street", 2 would get me "Anytown", etc.
Here is my code so far:
Public Function fragmentAddress(address As String, numberofcommas As Integer) As String
seen = 1
lastComma = -1
Dim x As Long
Dim frag As Long
For x = 0 To Len(address)
If Mid(address, x, 1) = "," & numberofcommas = seen Then
Exit For
ElseIf Mid(address, x, 1) = "," & numberofcommas <> seen Then
seen = seen + 1
lastComma = x
End If
Next
frag = Mid(address, lastComma + 1, seen - lastComma)
fragmentAddress = frag
I have not implemented the ability to handle the final value yet, but it does not give me any outputs, only outputting a "#VALUE!" error when I attempt to give it the input
=fragmentAddress("3 Ashley Close, Charlton Kings",1)
I have some experience with programming, but this is my first time writing anything in VBA.
Any help would be appreciated, thank you.
Not exactly sure what your question is, but this is simpler:
Public Function GetAddressFragment(ByVal Address As String, ByVal Index As Integer) As String
Dim addr() As String
addr = Split(Address, ",")
On Error Resume Next
GetAddressFragment = Trim(addr(Index - 1))
End Function
In excel, each cell in Column A has 1-6 urls in random order separated by ";".
I'm trying to extract urls from each domain, and place them in according columns.
http:/i.stack.imgur.com/J7UJg.jpg (// subbed with / to post)
For example, A2, would have the following,
http:/randomwebsite.com/content/mieIEe;
http:/examplesite.io/jiefaiwjf0293845983725kjsdaf;
http:/randomwebsite.com/img/fjioewqa;
https:/www.anotherrandomsite.com/watch=9hDEOjefls;
http:/www.anotherexample.com/5053/765437/qwreja;
http:/random.com/jfieJOJd344
B1 - F1 would each be columns for the different domains. B1 would be a column for randomwebsite.com, C1 would be for anotherrandomsite.com, .. and so forth.
The results I would want in this case is to have each corresponding url from column A, to show in each designated column. Like the first url "http:/randomwebsite.com/content/mieIEe" to show in B2, and if same domains come up twice or more, separate them with "," within the same cell as B2 would be "http:/randomwebsite.com/content/mieIE,http:/randomwebsite.com/img/fjioewqa".
I've tried putting the following in B2 and on..
=IFERROR(MID($A2,FIND(B$1,$A2),FIND("; ",$A2)-1),"")
&IFERROR("; "&MID($A2,FIND(B$1,$A2,FIND(B$1,$A2)+1),FIND("; ",$A2)-1),"")
Does kinda work, but I ran into a problem of determining the actual length of each url.
Main issues are:
some domains are listed twice or more
not all domains start with http/s www, or end with com
Would there be any standard function methods to solve this within a single cell?
I have no experience with VBA.
After looking at your post a little longer I realised that you want the URLS in column A to be distributed over the columns B to F and placed in the column having the domain name in its first row (B1:F1). The function you have provided is probably as good as it can be if you restrict yourself to worksheetfunctions.
I have put together a little VBA function that might do the job for you in a slightly different manner:
Function furl(urls, dom) ' filter URLs from string urls that belong to domain dom
Dim uarr, retval$, i%, j%
retval = ""
uarr = Split(urls, "; ")
For i = LBound(uarr) To UBound(uarr)
If (InStr(uarr(i), dom) > 0) Then retval = retval & "; " & uarr(i)
Next i
furl = Mid(retval, 3)
End Function
First I split the string into its individul urls using your separator "; ". I then run through all the resulting array elements in a for look and check for dom to appear there as a substring. If it does i add it to my retval string. This string is then returned by assigning it to the function itself (furl=mid(retval,3)). The mid(retval,3) removes the first two characters of the string.
You should "insert" a "Module" into the VBAproject of your current file and place the above code into that module. In your worksheet you can then use the function just like any other worksheetfunction like in cell B2:
=furl($a2,b$1)
In the column headers B1:F1 you should enter the minimum version of your URLs like 'randomwebsite.com', leaving out all optional stuff like 'http://' and 'www.'.
UPDATE
Yes, pnuts has a point with his comment!
I updated my function. Now it checks for possible word boundaries (any of the characters in "./") before and "/?#" after the given domain name:
Function furl(urls, dom) ' filter URLs from string urls that belong to domain dom
Dim uarr, retval$, i%, j%, lft$, ldom%
retval = ""
ldom = Len(dom)
uarr = Split(urls, "; ")
For i = LBound(uarr) To UBound(uarr)
j = InStr(uarr(i), dom)
If (j > 0) Then
' "word boundary"-char before the found position:
If (j = 1) Then lft = "." Else lft = Mid(uarr(i), j - 1, 1)
' right boundary left boundary
If (InStr("/?#", Mid(uarr(i), j + ldom, 1)) > 0 And InStr("./", lft)) Then
retval = retval & "; " & uarr(i)
End If
End If
Next i
furl = Mid(retval, 3)
End Function
I tested it and it works. Now I hope I can convince my downvoters to have mercy with me again ;-)
OR maybe, explain why they downvoted ...
OR maybe, even come up with a better solution - that would help us all!
I would like to download prices from the internet. The concept works, when I define symb as a constant value (e.g. K15). But now, I want to download data from different links, where the part symb changes according to the value of the cells G13 to G22 in my spreadsheet. (In other words, I want to go through each row from G13 to G22 - each containing a different value for symb - and download the data from the respective link).
I tried that with a simple loop, defining the variable symb in each one of the loops:
For i = 1 To 10
Symb = Worksheets("Futures").Range("G12").Offset(i, 0).Value
Set qt = querysheet.QueryTables.Add( _
Connection:="URL;" & "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symb & ".cbt&f=sl1d1t1c1ohgv&e=.csv", _
Destination:=querysheet.Cells(5 + i, 1))
Next i
Obviously, it doesn't work like this. I assume that it is not possible to define a variable within the loop, is it? Can somebody give me a hint how I can make that work?
There's something worng with your Connection String. When I get rid of the .cbt in the URL string, it works. Or, you may have forgotten to include some letters, so debug it in your browser and get the Connection string correct and it should work.
You may also want to modify the destination, like so, and refresh the table:
Set qt = querySheet.QueryTables.Add( _
Connection:="URL;" & "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symb & "&f=sl1d1t1c1ohgv&e=.csv", _
Destination:=querySheet.Cells(5, 1))
qt.Refresh
you could use an array like this
symb(1 to 10) as String
for i=1 to 10
symb(i)=cells(i,1)
next i