Excel Vba bold some text on a string - string

i need some help with excel.
I have a cell that get value by macro with code:
Range("A1").Value = "This Year we are having our guest " &Guest_name &" who is currently " &Guest_age &"years old, spending holidays with us"
So i'm just wondering how can I get the Guest_name and Guest_age to be bold.
Thanks

Here is one version of the answer. Using Characters to instruct vba where to start and end.
Sub test()
Dim guest_name, guest_name_len As Integer
Dim guest_age, guest_age_len As Integer
guest_name = "tester"
guest_name_len = Len(guest_name)
guest_age = "999"
guest_age_len = Len(guest_age)
Debug.Print guest_name_len & " / " & guest_age_len
Range("A1").Value = "This Year we are having our guest " & guest_name & " who is currently " & guest_age & "years old, spending holidays with us"
With Range("A1").Characters(Start:=35, Length:=guest_name_len).Font '35 characters counted (this year....)
.FontStyle = "bold"
End With
With Range("A1").Characters(Start:=35 + guest_name_len + 18, Length:=guest_age_len).Font '18 characters counted (who is... years old)
.FontStyle = "bold"
End With
End Sub

Use InStr to locate each within the range's .value2 property and apply .font.bold = true to the substring's .Characters property.

Related

Excel vba how to disallow Excel converting a month name with number into date? [duplicate]

This question already has answers here:
Prevent Excel to format string as date
(2 answers)
Closed last year.
Sub test1()
MonthYear = MonthName(Right(2009, 2)) & " " & Left(2009, 2) 'locals window show "September 20"
Range("A1").Value = MonthYear '20-Sep is shown in cell A1 where the formula box is 20-09-2022
Range("A1").Value = "'" & MonthYear '---> my solution for the time being
End Sub
What I want is in cell A1 show September 20 (just like in the Locals Window), as a text not a date.
What I've tried so far :
Sub test2()
MonthYear = "01-" & MonthName(Right(2009, 2)) & "-20" & Left(2009, 2) 'locals window show "01-September-2020"
Range("A1").Value = MonthYear '01-Sep-20 is shown in cell A1 where the formula box is 01-09-2020
Range("A2").Value = Format(MonthYear, "mmmm yy") 'AGAIN, 20-Sep is shown in cell A1 where the formula box is 20-09-2022
Range("A1").NumberFormat = "mmmm yy" 'another solution for the time being
End Sub
My question:
How do I have to write the code, so it put the result in the cell directly as a text September 20 ?
Any kind of help would be greatly appreciated.
Thank you in advanced 🙏.
Apply text formatting first:
Range("A1").NumberFormat = "#"
Range("A1").Value = MonthYear

Sequencing a part number using User Form

I am completely new in VBA or programming. Right now I am developing a macro for a manufacturing site that inputs process data using Excel's User Forms. One of the things I want this macro to do is to automatically create run numbers for each process. The run number syntax we use is as follows:
V1.yy.mm.dd-1
V1.yy.mm.dd-2
V1.yy.mm.dd-3
Ex V1.20.04.29-1
The way I am trying to set up the run number creation is that when I select an item from a ComboBox the part number gets created into a TextBox to later be submitted into the corresponding database. I am not sure how to create a sequence after the Prefix = V1.yy.mm.dd-, I tried to use a CountIf application that would count the number of Prefixes with the same date in the spreadsheet for sequencing, but it seems the function does not work for partial matches. I tried to use the following but I can't get it to work. I am sure there are simpler ways to do this, can you give me a few suggestions? Thanks
This is the code I wrote so far:
Private Sub ComboBox1_Change()
If Me.ComboBox1.Value <> "" Then
Dim Prefix As String
Dim mm, dd, yy As String
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("2- V1 Loading (2)")
Dim s As Long
s = 1 + sh.Application.Count(Application.Match(Prefix, Range("B:B"), 0))
mm = Format(Date, "mm")
dd = Format(Date, "dd")
yy = Format(Date, "yy")
Prefix = "V1." & yy & "." & mm & "." & dd & "-"
v1 = "V1." & yy & "." & mm & "." & dd & "-" & "" & s
Me.TextBox6.Value = v1
End If
Maybe something like this ?
Private Sub ComboBox1_Change()
If Me.ComboBox1.Value <> "" Then
Set sh = ThisWorkbook.Sheets("2- V1 Loading (2)")
oDate = Format(Date, "yy.mm.dd")
oConst = "V1." & oDate & "-"
Range("B1:B10000").Copy Destination:=Range("zz1") 'copy all the item to helper column
Range("zz:zz").Replace What:=oConst, Replacement:="" 'get only the number from all the items with the current date
nextNum = Application.Max(Range("zz:zz")) + 1 'get the next number
MsgBox oConst & CStr(nextNum) 'this line only for checking
Range("zz:zz").ClearContents 'clear the helper column
Me.TextBox6.Value = oConst & CStr(nextNum)
End If
But this assuming that the item number in columns B is only at the same day.
If for example there is a forgotten data from any day before the current day, and this want to be inputted with that day and the next number, it need an input box or maybe a cell in sheet where the value is that day, then it will give the last number of that day.
Suppose the data in column B is something like below:
If the code is run today, it will show V1.20.04.30-4 as the next number. With the same data like above, if the code is run tomorrow, it will give V1.20.05.01-1.
To get the next number from yesterday (29 Apr 2020), the code need more line - which is to know on what day the code must get the next number.
Or this kind of line maybe is shorter:
oConst = "V1." & Format(Date, "yy.mm.dd") & "-"
nextNum = oConst & Application.WorksheetFunction.CountIf(Range("B:B"), "*" & oConst & "*") + 1
MsgBox nextNum
There are a few ways you could go about this but I'd say the easiest would be to put the incrementing run number in a separate cell somewhere on your worksheet (or another one if you want) to reference each time.
For example:
When the data is entered onto your 'database' sheet, write the run value to ThisWorkbook.Sheets("2- V1 Loading (2)").Range("AZ1").
Then in your code check that value like so:
Private Sub ComboBox1_Change()
If Me.ComboBox1.Value <> "" Then
Dim Prefix As String
Dim mm, dd, yy As String
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("2- V1 Loading (2)")
Dim s As Long
s = 1 + sh.Range("AZ1").Value
mm = Format(Date, "mm")
dd = Format(Date, "dd")
yy = Format(Date, "yy")
Prefix = "V1." & yy & "." & mm & "." & dd & "-"
v1 = "V1." & yy & "." & mm & "." & dd & "-" & s
Me.TextBox6.Value = v1
Presuming that the reference numbers are written to column B of the 2- V1 Loading (2) tab then the next number must always be the one found at the bottom of the column + 1. If there is no number for that date than the new sequential number should be 1. The code below implements that method
Function NextRef() As String
' 016
Dim Fun As String
Dim Counter As Integer
Dim Rng As Range
Dim Fnd As Range
Dim Sp() As String
Fun = Format(Date, """V1.""yy.mm.dd")
With ThisWorkbook.Worksheets("2- V1 Loading (2)")
' start in row 2 (row 1 holding column captions)
Set Rng = .Range(.Cells(2, "B"), .Cells(.Rows.Count, "B").End(xlUp))
End With
If Rng.Row > 1 Then ' skip, if the column is empty
' finds the first occurrence of Ref from the bottom
Set Fnd = Rng.Find(What:=Fun, _
After:=Rng.Cells(1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchDirection:=xlPrevious)
If Not Fnd Is Nothing Then
Sp = Split(Fnd.Value, "-")
If UBound(Sp) Then Counter = Val(Sp(1))
End If
End If
NextRef = Fun & -(Counter + 1)
End Function
You can use the function simply like ComboBox1.Value = NextRef. However when and how to call that line of code is a bit unclear in your design as published. Especially, it's not clear why you would want it in a ComboBox at all, given that the box might also contain other information. Your idea to use the Change event may not work as intended because that event occurs with every letter the user types. I have tested this:-
Private Sub ComboBox1_GotFocus()
' 016
With ComboBox1
If .Value = "" Then .Value = NextRef
End With
End Sub
The next reference number is inserted as soon as you click on the ComboBox. It works but it doesn't make sense. I think now that you have the function that does the work you will find a way to deploy it. Good luck.

How to use stdeva in an excel macro

this line is giving me an error,please help me to troubleshoot
ActiveCell.Formula = "=STDEVA(range(" & """" & area & """" & ")"
here area is a string variable which is having the value it supposed to have just fine
So the main issue is syntax and more specifically the quotation marks I guess,any help is appreciated,even though I can use stdev I still like to use stdeva in my macro although the difference is very subtle.
This assumes that area is a String`:
Sub gahgsd()
Dim area As String
area = "A1:A4"
ActiveCell.Formula = "=STDEVA(" & Range(area).Address & ")"
End Sub
or:
Sub gahgsd()
Dim area As String
area = "A1:A4"
ActiveCell.Formula = "=STDEVA(" & area & ")"
End Sub

How to display 'userUnemployment' in the message box when certain choices are picked in the Userform

I want to display the unemployment numbers for the specific year and race chosen by the user in a Userform. The userUnemployment will be static numbers that specific to certain conditions being met.
I have tried various If and Else, If and ElseIfs
Private Sub buttonOk_Click()
Dim year, race As String
Dim userUnemployment As String
'first find the year
If five Then
year = "2005"
ElseIf six Then
year = "2006"
ElseIf seven Then
year = "2007"
ElseIf eight Then
year = "2008"
ElseIf nine Then
year = "2009"
ElseIf ten Then
year = "2006"
ElseIf eleven Then
year = "2007"
ElseIf twelve Then
year = "2008"
ElseIf thirteen Then
year = "2009"
ElseIf fourteen Then
year = "2009"
ElseIf fifteen Then
year = "2006"
ElseIf sixteen Then
year = "2007"
ElseIf seventeen Then
year = "2008"
ElseIf eighteen Then
year = "2009"
End If
'now find the race for that year
If white Then
race = "white"
ElseIf black Then
race = "black"
ElseIf hispanic Then
race = "hispanic"
ElseIf asian Then
race = "asian"
End If
'now find the unemployment rate for the things specified
If year = "2005" & race = "white" Then
userUnemployment = "3.48"
ElseIf year = "2005" & race = "black" Then
userUnemployment = "5"
End If
MsgBox ("The year is " + year + ", and your race is " + userUnemployment + " " + race)
End Sub
I want the message to display the userUnemployment number specified. I only listed two choices because I have not found the other unemployment numbers I want to use yet. So as long as I can get it to work for those two then I can figure the rest out.
On a worksheet (I used Sheet1), create a table like this to hold your Unemployment Rates (Note that I only populated the values that you provided in your question):
You haven't shown what your userform looks like, but I assume it's got Option Buttons (radio buttons) for selecting the Year and the Race. In general, for this use case, a much cleaner solution would instead to use either Listboxes or Comboboxes. I decided to use Listboxes for this example. My userform looks like this:
And here is the full userform code. The UserForm_Initialize code populates the listboxes based on the table. Then the btnOK_Click() verifies that a Year and a Race have been selected and then finds the corresponding Unemployment Rate using a VLookup. It then outputs a MsgBox displaying the results:
Private Sub btnCancel_Click()
Unload Me
End Sub
Private Sub btnOK_Click()
Dim ws As Worksheet
Dim sRace As String
Dim lYear As Long
Dim lRaceCol As Long
Dim dUnemployment As Double
If Me.listYear.ListIndex = -1 Then
Me.listYear.SetFocus
MsgBox "Must select a year.", , "Error"
Exit Sub
End If
If Me.listRace.ListIndex = -1 Then
Me.listRace.SetFocus
MsgBox "Must select a race.", , "Error"
Exit Sub
End If
Set ws = ThisWorkbook.Worksheets(1)
lYear = Me.listYear.List(Me.listYear.ListIndex)
sRace = Me.listRace.List(Me.listRace.ListIndex)
dUnemployment = WorksheetFunction.VLookup(lYear, ws.Range("A1").CurrentRegion, WorksheetFunction.Match(sRace, ws.Rows(1), 0), False)
MsgBox "Year: " & lYear & Chr(10) & _
"Race: " & sRace & Chr(10) & _
"Unemployment Rate: " & dUnemployment
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Me.listYear.List = ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp)).Value
Me.listRace.List = Application.Transpose(ws.Range("B1", ws.Cells(1, ws.Columns.Count).End(xlToLeft)).Value)
End Sub
Here's what it looks like in action:
I would use the msgbox like this: "Msgbox = "The year is " & year & " and your race is " & usereunemployment". This should display the message that you want to see....

Convert month name into number

I have dropdown box with months populated. When a month is selected I would like to then convert it to the month number is there a function that can do this?
Eg. September = 9
Another way
Excel Formula
=MONTH(1&A1)
VBA
Sub Sample()
Dim MonthNm As String
MonthNm = "September"
Debug.Print Month(DateValue("01 " & MonthNm & " 2012"))
End Sub
or
Sub Sample()
Dim MonthNm As String
MonthNm = "September"
Debug.Print Application.Evaluate("=MONTH(1&" & Chr(34) & MonthNm & Chr(34) & ")")
End Sub
Replace
Try this...
=MONTH(DATEVALUE(A1&"1"))
Where A1 cell contains month name.
Sub month()
Dim monthh As Integer
monthh = month(Date)
MsgBox monthh
End Sub
try this.
another excel formula where A1 is the cell id with month name:
=TEXT(DATEVALUE(A1&" 1"), "m")
This solution didn't work for me (Excel 2010), I had to shorten the month name to 3 characters and add the day number in front of the shortened string.
=MONTH(1&LEFT(A1;3))
Another VBA solution
For the sake of the art in addition to Siddharth's valid answer :-)
Sub SampleTM()
Dim MonthNm$: MonthNm = "September"
Debug.Print MonthNm2Num(MonthNm)
End Sub
Function MonthNm2Num(ByVal MonthNm) As Long
MonthNm2Num = Format(CDate(MonthNm & "/1 0"), "m") * 1&
End Function

Resources