VBA StringBetween - vba

i have a little problem.
I want to get the Version Number from my Site, which is stored like that:
<version>1</version>
How can i get the Number between that 2 Strings into a variable?
Im completly new to vba and just need it for a simple check.
Thanks
//EDIT:
Tried now:
Data = .responseText
version = Replace(Replace(Data, "<version>", vbNullString), "</version>", vbNullString)
If version > Cells(2, 3) Then
strTitle = "new version"
strPrompt = "new version available"
iRet = MsgBox(strPrompt, vbOKOnly + vbExclamation, strTitle)
End If
In the Cell there is a "1" also on the site a:
<version>1</version>
But everytime i run it the msgbox pop up..
I just testewd it. The version aswell the cell output = 1. DOnt know why it wont work then

in VBA:
Dim Data As String, cleanData As String
Data = "<version>1</version>"
cleanData = Replace(Replace(Data, "<version>", vbNullString), "</version>", vbNullString)
In Excel where B57 is the text "1":
LEFT(RIGHT(B57, LEN(B57) - FIND(">",B57)), 1)

... Given that you know it will be surrounded by those 2 words specifically, you oculd use something like:
MyVersion = Replace(Replace(x, "<version>", ""), "</version>", "")

If this is already stored in a string, then a simple answer might be:
replace(
replace(myString,"<version>","")
,"</version>","")
Basically, just replace the first half of your string with nothing, then replace the second half with nothing, leaving just the number.

Related

Use image to open record in another form

I am really struggling and wondered if someone could help please? I am trying to set up a database with images which I have done and used the file path of my pictures. It works well and that is great, but the next step is to have a form that just displays the pictures from each record to act as a catalogue and then When you click on a particular picture in that form it opens up another form that contains all the records and goes directly to that specified record. We have managed to get it to work for the first picture and record but can't work out how to make it go to the next record for the next image. I am trying to use a multi line form for this and only have the picture visible. I am just using a basic code as I have only just started with VBA but I believe this may not work. Can someone please help advise me?
I have used the following code which was suggested online for working with pictures and then there are a couple of other vba code to add to it. I need to create a catalogue inventory but we want to click on the picture of the inventory item which then opens a form with all the detail. I have found a work around with using the continous form and transparent buttons which take you to the specific record but you can't seem to change the layout. Ideally I am looking to have a form with just the images in a grid style going across the page and not just a list going down the page...if that makes sense?
Option Compare Database
Option Explicit
Public Function DisplayImage(ctlImageControl As Control, strImagePath As Variant) As String
On Error GoTo Err_DisplayImage
Dim strResult As String
Dim strDatabasePath As String
Dim intSlashLocation As Integer
With ctlImageControl
If IsNull(strImagePath) Then
.Visible = False
strResult = "No image name specified."
Else
If InStr(1, strImagePath, "\") = 0 Then
' Path is relative
strDatabasePath = CurrentProject.FullName
intSlashLocation = InStrRev(strDatabasePath, "\", Len(strDatabasePath))
strDatabasePath = Left(strDatabasePath, intSlashLocation)
strImagePath = strDatabasePath & strImagePath
End If
.Visible = True
.Picture = strImagePath
strResult = "Image found and displayed."
End If
End With
Exit_DisplayImage:
DisplayImage = strResult
Exit Function
Err_DisplayImage:
Select Case Err.Number
Case 2220 ' Can't find the picture.
ctlImageControl.Visible = False
strResult = "Can't find image in the specified name."
Resume Exit_DisplayImage:
Case Else ' Some other error.
MsgBox Err.Number & " " & Err.Description
strResult = "An error occurred displaying image."
Resume Exit_DisplayImage:
End Select
End Function

How to get Selection.Text to read displaytext of Macro field code

I'm having some trouble figuring this out, and would really appreciate some help. I'm trying to write a macro that uses the selection.text property as a Case text-expression. When the macro is clicked in Microsoft Word, the selected text is automatically set to the DisplayText. This method worked great for the formatting via Selection.Font.Color for a quick and dirty formatting toggling macro, but it doesn't work for the actual text.
When debugging with MsgBox, it is showing a box (Eg: □ ) as the value.
For example,
Word Field Code:
{ MACROBUTTON Macro_name DisplayText }
VBA Code run when highlighting "DisplayText" in Word:
Sub Macro_name()
Dim Str As String
Str = Selection.Text
MsgBox Str
Select Case Str
Case "DisplayText"
MsgBox "A was selected"
Case "B"
MsgBox "B was selected"
End Select
End Sub
What is output is a Message Box that only shows □
When I run this macro with some regular text selected, it works just fine.
My question is this: Is there a way to have the macro read the displaytext part of the field code for use in the macro?
You can read the field code, directly, instead of the selection (or the Field.Result which also doesn't give the text).
It's not quite clear how this macro is to be used throughout the document, so the code sample below provides two variations.
Both check whether the selection contains fields and if so, whether the (first) field is a MacroButton field. The field code is then tested.
In the variation that's commented out (the simpler one) the code then simply checks whether the MacroButton display text is present in the field code. If it is, that text is assigned to the string variable being tested by the Select statement.
If this is insufficient because the display text is "unknown" (more than one MacroButton field, perhaps) then it's necessary to locate the part of the field code that contains the display text. In this case, the function InstrRev locates the end point of the combined field name and macro name, plus the intervening spaces, in the entire field code, searching from the end of the string. After that, the Mid function extracts the display text and assigns it to the string variable tested by the Select statement.
In both variations, if the selection does not contain a MacroButton field then the selected test is assigned to the string variable for the Select statement.
(Note that for my tests I needed to use Case Else in the Select statement. You probably want to change that back to Case "B"...)
Sub Display_Field_DisplayText()
Dim Str As String, strDisplayText As String
Dim textLoc As Long
Dim strFieldText As String, strMacroName As String
Dim strFieldName As String, strFieldCode As String
strDisplayText = "text to display"
If Selection.Fields.Count > 0 Then
If Selection.Fields(1).Type = wdFieldMacroButton Then
strFieldName = "MacroButton "
strMacroName = "Display_Field_DisplayText "
strFieldCode = strFieldName & strMacroName
Str = Selection.Fields(1).code.text
textLoc = InStrRev(Str, strFieldCode)
strFieldText = Mid(Str, textLoc + Len(strFieldCode))
MsgBox strFieldText
Str = strFieldText
'If InStr(Selection.Fields(1).code.text, strDisplayText) > 0 Then
' Str = strDisplayText
'End If
End If
Else
Str = Selection.text
End If
Select Case Str
Case strDisplayText
MsgBox "A was selected"
Case Else
MsgBox "B was selected"
End Select
End Sub

Debugging "Search for Name" Code in VBA

I have solid experience in C++ but am still getting used to the syntax of VBA and I think that's what's tripping me up in my code.
What I'm trying to do is have a button that asks the user for a name. If the name entered is in column B, then tell the user the name was found and select where it is (no problem with this). If the name is not found, then ask if the user wants to try another name (no problem with this, either).
Where I'm having trouble is with the "Cancel" buttons. At any time, I want the user to be able to hit "Cancel" and immediately stop the loop, but stay in the sub because I'll be adding to this later.
Here's the code:
Dim inputName As String
Dim row As Integer
Dim i As Integer
Dim tryAgainResponse As Integer
tryAgainResponse = vbOK
'Ask user for name they would like to replace'
inputName = InputBox("What is the name of the person you would like to find? (First Last)")
'Find the row that the name is located and tell the user where it is'
Do While tryAgainResponse = vbOK
For i = 1 To 1000
If Cells(i, 2).Value = inputName Then
MsgBox ("Found the name! It's located at cell B" & i & ".")
ActiveSheet.Cells(i, 2).Select
tryAgainResponse = 0
Exit Do
End If
Next i
tryAgainResponse = MsgBox("We didn't find the name you were looking for. Please try again.", vbOKCancel)
If tryAgainResponse = vbCancel Then
Exit Do
End If
inputName = InputBox("What is the name of the person you would like to find? (First Last)")
Loop
I've tried plenty of things, but the main error is when you hit cancel for the first MsgBox, it tells you the name was found in the first blank square.
Any help or suggestions would be greatly appreciated! This is my first VBA program, so it's not the prettiest, but it's definitely a lot of fun. Thanks!
I'm not sure if I'm understanding what you're asking for, and I can't comment for clarification, but I think your hang up is that when you click cancel on the INPUT box, your input box is returning a blank string, and the rest of your code is then finding a blank cell.
Use the Application.Input Method, declare your input string as a variant, and test if it is false. If it is, use an Exit Sub to exit the macro. You could also test if your input string = "" and then exit the macro if true with the code you have.
From MrExcel
There are 2 versions of InputBox in VBA.
The InputBox Function is called without an object qualifiier and returns the contents of the text box or a zero-length string ("") if the user clicks Cancel.
The InputBox Method is a member of the Application object, so it is called by using Application.InputBox. It returns the contents of the text box or False if the user clicks Cancel. It is more versatile than the InputBox Function because it has a Type argument which specifies the return data type.
The function InputBox() will return an empty string if cancelled. The empty string will compare equal to the first cell that is empty.
Here's the doc of the function: http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Replace Underscores characters with Space inside a String value

This is a rather simple question.
I have a date variables formated like: 25_December_2010
I would like a statement or a bit of code in the VBA macro that will transform that string value from: 25_December_2010 to 25 December 2010.
Somehow be able to remove the underscores from inside the String value....
As I mentioned in comments, use code below:
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate,"_"," ")
I wanted something similar in a macro I'm using for data cleaning so I took #simoco's answer and created a simple but mostly safe macro/sub.
Sub ConvertSpaceToUnderscore()
Dim strCellValue As String
' Use basic error handling if more than 1 cell is selected, or
' possibly if something that isn't a cell is selected.
On Error GoTo SelectionTooBig
strCellValue = Selection.Value
strCellValue = Replace(strCellValue, " ", "_")
Selection.Value = strCellValue
On Error GoTo 0
' Exit the sub if things went well
Exit Sub
SelectionTooBig:
MsgBox "Please select one cell at a time.", vbCritical, "Selection too large"
End Sub

Excel headers/footers won't change via VBA unless blank

Disclaimer: It's been a few years since I worked (a lot) with VBA, so this might be an issue caused by confusing myself with what is essentially a very different language from what I usually deal with.
So; I've got a workbook (Excel 2010) with multiple sheets (20+), most of whom are multi-page. To make things easier when printing everything, I want to add some sheet-specific headers with amongst others the name of the sheet, number of pages and so on.
I've written a tiny function that should (in theory) do this for me by iterating over all the sheets setting the header. However, for some reason it only works if the header is empty; if it already has a value it refuses to overwrite for some unknown reason.
Dim sheetIndex, numsheets As Integer
sheetIndex = 1
numsheets = Sheets.Count
' Loop through each sheet, but don't set any of them to active
While sheetIndex <= numsheets
Dim sheetname, role, labeltext As String
sheetname = Sheets(sheetIndex).name
role = GetRole(mode)
labeltext = "Some text - " & sheetname & " - " & role
With Sheets(sheetIndex).PageSetup
.LeftHeader = labeltext
.CenterHeader = ""
.RightHeader = "Page &[Page] / &[Pages]"
.LeftFooter = "&[Date] - &[Time]"
.CenterFooter = ""
.RightFooter = "Page &P / &N"
End With
sheetIndex = sheetIndex + 1
Wend
I found a solution that seems to work for replacing text. For whatever reason, in the macro, you need to include the header/footer format character codes in order for it to work properly.
This code worked to replace existing header text with new information:
Sub test()
Dim sht As Worksheet
Set sht = Worksheets(1)
sht.PageSetup.LeftHeader = "&L left text"
sht.PageSetup.CenterHeader = "&C center Text"
sht.PageSetup.RightHeader = "&R right text"
End Sub
Without the &L, &C, and &R codes before the text, I could not get it to work.
Some interesting behavior I found is that if you use the following code:
.CenterHeader = "&L some text"
it will actually put the some text in the LeftHeader position. This led me to believe that the formatting codes were very important.
The line Application.PrintCommunication = False (which is added by the macro recorder) before doing PageSetup screws up the formating via VBA.
If your code has got this line in it, try removing it. That solved my problem with setting the header and footer via VBA.
I've read StackOverflow for years and this is the first time I've actually been able to post a solution ... hope it helps someone!! Also, you need to remember, I am a CPA not a programmer ;-)
I am reading some values from the ActiveSheet to populate the header. The application is a tax election that will be sent with a tax return so it must have the taxpayer's name and social security number at the top.
Sub PrintElection()
' Print preview the MTM Election
If Range("Tax_Year").Value = Range("First_MTM_year").Value Then
ActiveSheet.PageSetup.LeftHeader = Format(Worksheets("Election").Range("Taxpayer_Name").Value)
ActiveSheet.PageSetup.RightHeader = Format(Worksheets("Election").Range("Taxpayer_SSN").Value)
ActiveWindow.SelectedSheets.PrintPreview
Else
MsgBox "The 'Effective For Tax Year' date must EQUAL the 'First MTM year' date", vbOKOnly, "Check Years"
Sheets("Roadmap").Select
Range("First_MTM_year").Select
End If
End Sub
It checks to see if the Mark-to-Market election year is the same as the election form then formats the election page.
I split the sheet print setup into 2 loops. First loop with Application.PrintCommunication = False I run the non-header/footer setup. I then set Application.PrintCommunication = True and run the header/footer setup in a second loop. Appears to run faster than in XL2003, and applies the header/footer correctly. Until MS fixes this bug, that works fine for me.