I am very new to VB macro.In sheet 3 i have three columns named "Country " "Provinces" and "Risk"
For "Provinces", values present are NB,NS,NF,PE. IN sheet5, i have written a code like
`(val) Like "*[HH,HHJ,qqw,www]" Then
to check if user has provided input like NB or like NB, NS or like PE only then corresponding values from Risk will get displayed. Now with the above code , if user is entering value as "," also results is getting displayed as , is present in the Like statement.
Kindly guide me.
You can't use VBA Like that way. Try:
X = "abc, NB"
If X Like "*NB" Or _
X Like "*NS" Or _
X Like "*NF" Or _
X Like "*PE" Then
Debug.Print "X is in the Maritimes"
End If
If you set Option Compare Text at the beginning of your macro, you don't have to Ucase the string being tested.
For complex comparisons, you can use Regular Expressions in VBA. You need to set the appropriate reference.
Related
In the following Subroutine, defining a two dimensional array doesn't seem to work with line continuation. TestArray1 initializes as expected, but when I add line continuation I get the message,
"Compile Error - Closing bracket missing".
(Actually I'm not sure of the exact wording in English, doing this in German. In German the error message is,
"Fehler beim Komilieren: Fehlende schliesende Klammer".
I'm sure the English is not far off.)
Why would this not work?
Sub TestArrays()
Dim TestArray1 As Variant, TestArray2 As Variant
TestArray1 = [{"1String1", "1String2", "1String3"; "2String1", "2String2", "2String3"; "3String1", "3String2", "3String3"}]
TestArray2 = [{"1String1", "1String2", "1String3"; _
"2String1", "2String2", "2String3"; _
"3String1", "3String2", "3String3"]}
End Sub
Don't use square brackets.
Square brackets in VBA DO NOT stand for "this is an array", even though it looks like it (if you're any familiar with JSON anyway), and even though it might work.
Square brackets in VBA stand for "this is an expression that the host application will be evaluating at run-time".
In other words, it's giving work to Excel's expression evaluation engine: it's not VBA, it's Excel. The syntax of whatever is inside a square-bracketed expression must be legal in Excel's formula bar1.
Use the Array standard VBA function to create an array in VBA:
TestArray1 = Array("1String1", "1String2", "1String3", "2String1", "2String2", "2String3", "3String1", "3String2", "3String3")
Split it up with a line continuation at any point between two strings:
TestArray1 = Array( _
"1String1", "1String2", _
"1String3", "2String1", _
"2String2", "2String3", _
"3String1", "3String2", _
"3String3")
Note that the inconsistent ; vs , separators are probably part of the problem: Excel formulas use your system's list separator character: that's the character you'll want to use in square-bracket expressions - but you don't need to do that, because you don't need any square-bracket expressions.
There is no syntax for inline-initializing a 2D array in VBA. Declare & size your array explicitly instead:
Dim my2D(1 To 10, 1 To 10)
my2D(1, 1) = "1string1"
'...
If you have that much hard-coded strings in your code, then you are coding data. Data belongs in storage, not in code. Read the data from a worksheet, you'll get a 2D variant array for free, with a one-liner, without abusing language syntax, and if the data needs to change, then the code doesn't:
Dim my2D As Variant
my2D = sourceRange.Value
1 unless it's a VBA foreign identifier, in which case Excel doesn't get to evaluate it. Just don't use square bracket expressions, they're confusing.
Trying to get data from Excel and merge it into Word using MailMerge (just like how it is done in this video).
However, fields aren't getting updated after running this code. VBA isn't throwing any error so looks like code is fine. Can you please help?
Sub getdata()
Dim numRecord As Integer
Dim myName As String
myName = InputBox("Enter the field name and relax!")
Set dsMain = ActiveDocument.MailMerge.DataSource
If dsMain.FindRecord(FindText:=myName, Field:="Fields") = True Then
numRecord = dsMain.ActiveRecord
End If
End Sub
Note: Data in Excel looks like this:
Fields First Layer Second Layer
CC 5 3
So when someone enters CC in Input box I want first_layer and Second_layer fields in word to get updated to 5 and 3 respectiely.
If you're running the mailmerge from Word, you don't actually need any VBA for this - it can all be done with a SKIPIF field. For example the following field code does the same as the macro in the video is supposed to:
{SKIPIF{FILLIN "Name to merge" \o}<> {MERGEFIELD Name}}
or:
{SKIPIF{FILLIN "Name to merge" \o}<> «Name»}
Note: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Nor is it practical to add them via any of the standard Word dialogues. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.
The problem that I'm facing is that I have an entire column that has text separated by _ that contains pixel size that I want to be able to extract but currently can't. For example:
A
Example_Number_320x50_fifty_five
Example_Number_One_300x250_hundred
Example_Number_two_fifty_728x49
I have tried using Substitute function to grab the numbers which works but only grabs the numbers when I need something like: 320x50 instead I'm getting 0, as I'm not sure how to exactly extract something like this. If it was consistent I could easily do LEFT or RIGHT formula's to grab it but as you can see the data varies.
The result that I'm looking for is something along the lines of:
A | B
Example_Number_320x50_fifty_five | 320x50
Example_Number_One_300x250_hundred | 300x200
Example_Number_two_fifty_728x49 | 728x49
Any help would be much appreciated! If any further clarification is needed please let me know and I'll try to explain as best as I can!
-Maykid
I would probably use a Regular Expressions UDF to accomplish this.
First, open up the VBE by pressing Alt + F11.
Right-Click on VBAProject > Insert > Module
Then you can paste the following code in your module:
Option Explicit
Public Function getPixelDim(RawTextValue As String) As String
With CreateObject("VBScript.RegExp")
.Pattern = "\d+x\d+"
If .Test(RawTextValue) Then
getPixelDim = .Execute(RawTextValue)(0)
End If
End With
End Function
Back to your worksheet, you would use the following formula:
=getPixelDim(A1)
Looking at the pattern \d+x\d+, an escaped d (\d) refers to any digit, a + means one or more of \d, and the x is just a literal letter x. This is the pattern you want to capture as your function's return value.
Gosh, K Davis was just so fast! Here's an alternate method with similar concept.
Create a module and create a user defined function like so.
Public Function GetPixels(mycell As Range) As String
Dim Splitter As Variant
Dim ReturnValue As String
Splitter = Split(mycell.Text, "_")
For i = 0 To UBound(Splitter)
If IsNumeric(Mid(Splitter(i), 1, 1)) Then
ReturnValue = Splitter(i)
Exit For
End If
Next
GetPixels = ReturnValue
End Function
In your excel sheet, type in B1 the formula =GetPixels(A1) and you will get 320x50.
How do you create a user defined function?
Developer tab
Use this URL to add Developer tab if you don't have it: https://www.addintools.com/documents/excel/how-to-add-developer-tab.html
Click on the highlighted areas to get to Visual Basic for Applications (VBA) window.
Create module
Click Insert > Module and then type in the code.
Use the user defined function
Note how the user defined function is called.
In Microsoft Excel file, I have a text in rows that appears like this:
1. Rc8 {[%emt 0:00:05]} Rxc8 {[%emt 0:00:01]} 2. Rxc8 {[%emt 0:00:01]} Qxc8 {} 3. Qe7# 1-0
I need to remove any text appearing within the flower brackets { and }, including the brackets themselves.
In the above example, there are three instances of such flower brackets. But some rows might have more than that.
I tried =MID(LEFT(A2,FIND("}",A2)-1),FIND("{",A2)+1,LEN(A2))
This outputs to: {[%emt 0:00:05]}. As you see this is the very first instance of text between those flower brackets.
And if we use this to within SUBSTITUTE like this: =SUBSTITUTE(A2,MID(LEFT(A2,FIND("}",A2)),FIND("{",A2),LEN(A2)),"")
I get an output like this:
1. Rc8 Rxc8 {[%emt 0:00:01]} 2. Rxc8 {[%emt 0:00:01]} Qxc8 {} 3. Qe7# 1-0
If you have noticed, only one instance is removed. How do I make it work for all instances? thanks.
Highlight everything
Go to replace
enter {*} in text to replace
leave replace with blank
This should replace all flower brackets and anything in between them
It is not that easy without VBA, but there is still a way.
Either (as suggested by yu_ominae) just use a formula like this and auto-fill it:
=IFERROR(SUBSTITUTE(A2,MID(LEFT(A2,FIND("}",A2)),FIND("{",A2),LEN(A2)),""),A2)
Another way would be iterative calculations (go to options -> formulas -> check the "enable iterative calculations" button)
To do it now in one cell, you need 1 helper-cell (for my example we will use C1) and the use a formula like this in B2 and auto-fill down:
=IF($C$1,A2,IFERROR(SUBSTITUTE(B2,MID(LEFT(B2,FIND("}",B2)),FIND("{",B2),LEN(B2)),""),B2))
Put "1" in C1 and all formulas in B:B will show the values of A:A. Now go to C1 and hit the del-key several times (you will see the "{}"-parts disappearing) till all looks like you want it.
EDIT: To do it via VBA but without regex you can simply put this into a module:
Public Function DELBRC(ByVal str As String) As String
While InStr(str, "{") > 0 And InStr(str, "}") > InStr(str, "{")
str = Left(str, InStr(str, "{") - 1) & Mid(str, InStr(str, "}") + 1)
Wend
DELBRC = Trim(str)
End Function
and then in the worksheet directly use:
=DELBRC(A2)
If you still have any questions, just ask ;)
Try a user defined function. In VBA create a reference to "Microsoft VBScript Regular Expressions 5.5. Then add this code in a module.
Function RemoveTags(ByVal Value As String) As String
Dim rx As New RegExp
rx.Global = True
rx.Pattern = " ?{.*?}"
RemoveTags = Trim(rx.Replace(Value, ""))
End Function
On the worksheet in the cell enter: =RemoveTags(A1) or whatever the address is where you want to remove text.
If you want to test it in VBA:
Sub test()
Dim a As String
a = "Rc8 {[%emt 0:00:05]} Rxc8 {[%emt 0:00:01]}"
Debug.Print RemoveTags(a)
End Sub
Outputs "Rc8 Rxc8"
I'm trying to create a simple calculator that shows the result of the calculations in a simple userform based on what the user enter in specific cells.
I'm using the
x.caption = Range("X").value
to display the value calculated.
So far so good, everything works.
I want also the label to show the corresponding unit for each field, say Kg. I tried adding:
And x.caption = "Kg"
to give:
x.caption = Range("X").value And x.caption = "Kg"
, but it neither gives me an error or actually works. How does one actually go about doing this?
String concatenation in VB is done with the "&" operator.
E.g.
x.caption = Range("X1").value & " Kg"