VBA Excel : A find and replace for charts titles - excel

I am making a macro that do a simple replacement in all chart titles. It works very well but suppress all format : italic, bold, ...
Here is the code :
Function trouverItalique(ByRef g As ChartObject)
Dim phrase As String
For i = 0 To Len(g.Chart.ChartTitle.Text)
If InStr(g.Chart.ChartTitle.Characters(i, 1).Font.FontStyle, "Italic") > 0 Then
phrase = phrase & g.Chart.ChartTitle.Characters(i, 1).Text
End If
Next
trouverItalique = phrase
End Function
Private Sub CommandButton1_Click()
Dim char As ChartObject
For Each s In ActiveWorkbook.Worksheets
For Each char In s.ChartObjects
If char.Chart.HasTitle Then
Dim phrase As String
'phrase = trouverItalique(char)
'char.Chart.ChartArea.AutoScaleFont = False
char.Chart.ChartTitle.Characters.Text = replace(char.Chart.ChartTitle.Characters.Text, TextBox1.Text, TextBox2.Text)
Dim index As Integer
'index = InStr(char.Chart.ChartTitle.Characters.Text, phrase)
'char.Chart.ChartTitle.Characters(index, Len(phrase)).Font.Italic = True
End If
Next
Next
End Sub
It works only for some cases and only for to keep the italic, I would like to keep bold and other formats. Do you have an idea to make my code works for any case ? Did I miss a cool mecanism to do the same thing without all of my peregrination ?

Try this:
Sub tester()
ReplaceTitle ActiveSheet.ChartObjects(1).Chart, "ghj", "fffffff"
End Sub
Private Sub ReplaceTitle(cht As Chart, ReplaceWhat As String, ReplaceWith As String)
Dim sTitle As String, pos
If cht.HasTitle Then
pos = InStr(cht.ChartTitle.Characters.Text, ReplaceWhat)
If pos > 0 Then
cht.ChartTitle.Characters(pos, Len(ReplaceWhat)).Text = ReplaceWith
End If
End If
End Sub

Related

How to remove the last character of a word in a text string and insert to another cell using VBA in Excel?

Everything is working except for that little comma in the 5th word. How to remove that? My code is as follows.
The text looks like this: The data as of 20.12.2019, and so on.
I only want 20.12.2019 without that comma. Any clue? Thanks.
Public Function FindWord(Source As String, Position As Integer)
Dim arr() As String
arr = VBA.Split(Source, " ")
xCount = UBound(arr)
If xCount < 1 Or (Position - 1) > xCount Or Position < 0 Then
FindWord = ""
Else
FindWord = arr(Position - 1)
End If
End Function
subroutine calls the function.
Sub InsertDate()
Sheets("Sheet1").Range("B3").Value = FindWord(Sheets("Sheet2").Range("A2"), 5)
End Sub
So just for fun, a short introduction to regular expressions (which, by no means, I am an expert in):
Sub Test()
Dim str As String: str = "The data as of 20.12.2019, and so on."
Dim regex As Object: Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "\b(\d{2}.\d{2}.\d{4})"
regex.Global = True
Debug.Print regex.Execute(str)(0)
End Sub
This would be good practice if your string won't follow that same pattern all the time. However when it does, there are some other good alternatives mentioned in comments and answers.
One option is to Replace:
Sub InsertDate()
With Sheets("Sheet1").Range("B3")
.Value = FindWord(Sheets("Sheet2").Range("A2"), 5)
.Value = Replace(.Value, ",", "")
End With
End Sub
This is still text-that-looks-like-a-date, so you can call DateValue to convert it.
.Value = Replace(.Value, ",", "")
.Value = DateValue(.Value) '<~ add this line

Excel - How to get contents of LeftHeader?

I need to do a find-and-replace on pagesetup leftheader. Caveat is that I need to know the contents of the LeftHeader in order to replace it using Substitute. For example, the LeftHeader could contain:
Sheet 1 - Updated - 1/12/19
Printed on 6/3/19
I would do a find-and-replace on 1/12/19 and 6/3/19 using below example code:
Sub FnR_HF()
Dim sWhat As String, sReplacment As String
Const csTITLE As String = "Find and Replace"
sWhat = InputBox("Replace what", csTITLE)
If Len(sWhat) = 0 Then Exit Sub
sReplacment = InputBox("With what", csTITLE)
With ActiveSheet.PageSetup
' Substitute Header/Footer values
.LeftHeader = Application.WorksheetFunction.Substitute( _
.LeftHeader, sWhat, sReplacment)
End With
End Sub
The above doesn't allow me to retrieve the contents of the LeftHeader. Can anyone help?
Rather than find/replace, why not just rename it?
It will generate a popup box with your existing header showing, and you can type over it with whatever you want the new header to be. Seems easier?
Sub MakeAHeader()
Dim aText As String, WS As Worksheet
Set WS = ActiveSheet
aText = InputBox("What do you want the header to be?", "Make Yo Header", WS.PageSetup.LeftHeader)
WS.PageSetup.LeftHeader = aText
MsgBox "This is your header: " & WS.PageSetup.LeftHeader
End Sub
Try this code
Sub FnR_HF()
Dim sWhat As String, sReplacment As String, sHeader As String
Const csTITLE As String = "Find and Replace"
sHeader = ActiveSheet.PageSetup.LeftHeader
sWhat = InputBox("Replace what", sHeader)
If Len(sWhat) = 0 Then Exit Sub
sReplacment = InputBox("With What", csTITLE)
sHeader = Replace(sHeader, sWhat, sReplacment)
ActiveSheet.PageSetup.LeftHeader = sHeader
End Sub

Excel VBA - how to find the largest substring value in a column

I have a column in a spreadsheet.
The format of the data in each cell is aa-0001-xx.
I need to examine the whole column to find the highest value of the sequence number. this would be the substring from column4 thru column7.
I can find the sequence number using Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4)
But I need to find the max sequence in the whole column.
I am doing this in VBA.
Any help would be appreciated.
Here is my code so far:
Private Sub CommandButton1_Click()
Dim sQuoteNumber As String
Dim sFileName As String
Dim sPathName As String
Dim checkit As String
'Log the Quote
'First, open the log file and determine the next sequential log number.
sPathName = "C:\Users\Rich\Documents\Bryan\BigProject\"
sFileName = "QuoteLog2016.xlsx"
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=sPathName & sFileName
'Create the new Quote Number
checkit = Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) ' This is a temp test line
If Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) = "" Then
sQuoteNumber = "16-0001"
Else
'find the biggest number
'Here I was looking to like pass the mid function to a Max function of some sort.
sQuoteNumber = "16-0002"
End If
MsgBox ("The new Quote Number is: " + sQuoteNumber)
'Save the log entry
Workbooks(sFileName).Close
All of the comments made to your answer would work well for you. It's also true that there's no evidence in your code at having attempted something, however rudimentary, and this is why answers to a rather trivial task are not forthcoming for you. Perhaps, in future, have a go at some kind of solution ( even if it feels more guesswork than anything) and people on this site will be much more supportive of you.
To set you on your way, you could make use of the Split() function which converts a String into a String array, separated by a nominated value - in the case of your quotations, you could use "-" as your separator. This might be easier than your Mid function and will deal with the case of different sized quotations.
The code below will get you started but you'd want some error handling in there to test, for example, that each cell splits appropriately or that any cells aren't blank. I'll leave all of that to you.
Option Explicit
Private mLastQuote As Long
Public Sub Test()
Initialise 'call this routine just once at the start of your project
MsgBox GetNextQuote(16) 'use the GetNextQuote() function to get next number
MsgBox GetNextQuote(16)
MsgBox GetNextQuote(16)
End Sub
Private Function GetNextQuote(prefix As Integer) As String
mLastQuote = mLastQuote + 1
GetNextQuote = CStr(prefix) & "-" & _
Format(mLastQuote, "000#")
End Function
Private Sub Initialise()
Const PATH_NAME As String = "C:\Users\Rich\Documents\Bryan\BigProject\"
Const FILE_NAME As String = "QuoteLog2016.xlsx"
Const QUOTE_COL As String = "B"
Dim wb As Workbook
Dim ws As Worksheet
Dim v As Variant
Dim r As Long
Dim parts() As String
Dim num As Long
Application.ScreenUpdating = False
Set wb = Workbooks.Open(PATH_NAME & FILE_NAME, True, True)
Set ws = wb.Worksheets("Sheet1")
'Read quote values into variant array
With ws
v = .Range(.Cells(2, QUOTE_COL), _
.Cells(.Rows.Count, QUOTE_COL).End(xlUp)) _
.Value2
End With
'Find max quote
For r = 1 To UBound(v, 1)
parts = Split(v(r, 1), "-") 'splits quote into 3 parts
num = CLng(parts(1)) 'index (1) is the middle part
If num > mLastQuote Then mLastQuote = num
Next
wb.Close False
Application.ScreenUpdating = True
End Sub

Excel VBA Regex

I need help extracting the following highlighted items delimited by REGEX
"delimeter is "YYYYMMDD-YYYYMMDD-CM""
Sub test()
Dim strg, text_string As String
text_string1 = "**mmmmm-02**-20141027-06240105-CM-STATS-HOURLY-DATA-perf.xlsx"
text_string2 = "**mmmm-mmmm-02**-20140811-12010069-CM-HOURLY-STATS-perf.xlsx"
End Sub
Sub test()
Dim text_string1 As String, myResult As String
text_string1 = "**mmmmm-02**-20141027-06240105-CM-STATS-HOURLY-DATA-perf.xlsx"
With CreateObject("VBScript.RegExp") '// Create Regex Engine
.Pattern = "[\d]{8}[\-][\d]{8}[\-]CM" '// Set match pattern
If .Test(text_string1) Then myResult = .Execute(text_string1)(0) '// If found return result.
End With
End Sub

VB6: Splitling with multi-multicharactered delimiters?

I have a problem with the split function I have currently. I am able to either split with 1 delimited only (split()) or split with many single characters (custom()). Is there a way to split this? Keep in mind that these delimiters are not in order.
"MY!!DATA##IS!!LOCATED##HERE!!IN!!BETWEEN##THE##ATS!!AND!!MARKS"
I need your help to get the following result
"MY" , "DATA" , "IS" , "LOCATED" , "HERE" , "IN" , "BETWEEN","THE", "ATS" , "AND", "MARKS"
thanks
Create a new VB6 EXE project and add a button to the form you will be given, and use the following code for the Button1_Click event:
Private Sub Command1_Click()
Dim myText As String
Dim myArray() As String
Dim InBetweenAWord As Boolean
Dim tmpString As String
Dim CurrentCount As Integer
CurrentCount = 0
myText = "MY!!DATA##IS!!LOCATED##HERE!!IN!!BETWEEN##THE##ATS!!AND!!MARKS"
For i = 1 To Len(myText)
If (Mid(myText, i, 1) = "#" Or Mid(myText, i, 1) = "!") And InBetweenAWord = True Then
CurrentCount = CurrentCount + 1
ReDim Preserve myArray(CurrentCount)
myArray(CurrentCount) = tmpString
tmpString = ""
InBetweenAWord = False
Else
If (Mid(myText, i, 1) <> "#" And Mid(myText, i, 1) <> "!") Then
tmpString = tmpString & Mid(myText, i, 1)
InBetweenAWord = True
End If
End If
Next
For i = 1 To CurrentCount
MsgBox myArray(i) 'This will iterate through all of your words
Next
End Sub
Notice that once the first For-Next loop is finished, the [myArray] will contain all of your words without the un-desired characters, so you can use them anywhere you like. I just displayed them as MsgBox to the user to make sure my code worked.
Character handling is really awkward in VB6. I would prefer using built-in functions like this
Private Function MultiSplit(ByVal sText As String, vDelims As Variant) As Variant
Const LNG_PRIVATE As Long = &HE1B6 '-- U+E000 to U+F8FF - Private Use Area (PUA)
Dim vElem As Variant
For Each vElem In vDelims
sText = Replace(sText, vElem, ChrW$(LNG_PRIVATE))
Next
MultiSplit = Split(sText, ChrW$(LNG_PRIVATE))
End Function
Use MultiSplit like this
Private Sub Command1_Click()
Dim vElem As Variant
For Each vElem In MultiSplit("MY!!DATA##IS!!LOCATED##HERE!!IN!!BETWEEN##THE##ATS!!AND!!MARKS", Array("!!", "##"))
Debug.Print vElem
Next
End Sub

Resources