I have put together the following code so that when I repeatedly press a shortcut, the number in a cell automatically switches formats between:
2020
2020A
2020E
2020A/E
2,020%
2,020x
2,020bps
Here's the code that isn't currently working:
Sub Number_Format_Cycle()
Dim x, myFormats
myFormats = Array("###0;(###0);-", "###0A;(###0)A;-", "###0E;(###0E);-", "###0A/E;(###0A/E);-", "#,##0.0%;(#,##0.0)%;0.0%", "#,##0.0x;(#,##0.0)x;0.0x", "#,##0bps;(#,##0)bps;0bps")
x = Application.Match(ActiveCell.NumberFormat, myFormats, False)
If IsError(x) Then x = 0
Selection.NumberFormat = myFormats((x Mod (UBound(myFormats) + 1)))
End Sub
Any help would be much appreciated
Cheers,
Thomas
You have to use a backslash (\) in order to add character literals to make them showing up exactly as typed.
Changing the myFormats assignment to the following codeline worked for me:
myFormats = Array("###0;(###0);-", "###0\A;(###0)\A;-", "###0\E;(###0\E);-", "###0\A\/\E;(###0\A\/\E);-", "#,##0.0%;(#,##0.0)%;0.0%", "#,##0.0x;(#,##0.0)x;0.0x", "#,##0\bp\s;(#,##0)\bp\s;0\bp\s")
Re-Check each number format you intend to add after a test setting against the array elements.
Caveat: I have to admit that I can't explain the last \bp\s format, nevertheless it works.
Related
For various reasons, I need to concatenate a text of the form [NAME].Value by changing the value of NAME to an inputbox entry.
Something like this:
Sub example()
data_in = InputBox("Give me something: ")
mystring1 = "[" & data_in & "].Value"
a = Evaluate(mystring1) 'I know this is wrong, but I don't know how to do so.
End Sub
I know it can be done in other ways, and the example in which I want to use this code is not exactly this one, and while it can be done in several ways here, in the original code it can only be done this way.
I want, based on the input in the imputbox, to concatenate the string in whatever way, and subsequently cast that string as code to store the value in another variable, to be used later in the code.
I am not able to get VBA to read the string text as code. I have seen that there is a way that consists of creating a macro from this first macro, execute it, and then delete the recently created macro. The problem with this solution is that doing that I can't save the variable when returning to the initial macro (I don't want to use global variables).
Surely there must be a way?
Thank you very much.
EDIT: The code above returns Error 2015
In order to use a string as if it was code, you can use the evaluate function (exists in most languages)
The official documentation mentions this example:
[a1].Value = 25
Evaluate("A1").Value = 25
trigVariable = [SIN(45)]
trigVariable = Evaluate("SIN(45)")
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1]
Set firstCellInSheet = _
Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")
I have figured out the easiest way to do it, sorry for posting the question so soon.
Thanks to #Andreas for the solution. I'll write it here in case than could be useful to someone.
Sub example()
data_in = InputBox("Give me something: ")
a = Range(data_in).Value
Debug.Print a
End Sub
In the end the simplest thing is the last thing you try...
I am trying to remove duplicate values except the first one.
My solution to this was to conditionally format all duplicates, then, working backwards, clear contents of the formatted cells. This would mean that the first one will stop being formatted once all duplicates are removed.
What I have been trying:
For i = LaC To 5 Step -1
LR = ws.Cells(Rows.Count, LaC).End(xlUp).Row
For j = 2 To LR
cond = (ws.Cells(j, i).DisplayFormat.Interior.ColourIndex.Value)
If cond = 22 Then
ws.Cells(j, i).ClearContents
End If
Next
Next
Basically, if I try ws.Cells(j, i).DisplayFormat.Interior.ColourIndex in the immediate window, it returns 22.
However, if I try this code, I get error:
Object doesn't support this property or method (Error 438)
Any assistance would be greatly appreciated.
If it is not necessary to use VBA you can get rid of duplicates in the GUI via “Data” → “Data Tools” → “Remove Duplicates”. Or, in current versions of Excel O365, you can use the UNIQUE-function like this
UNIQUE(A:A)
assuming your source data is in row A. This will keep up with changing data.
Check this line more carefully:
cond = (ws.Cells(j, i).DisplayFormat.Interior.ColourIndex.Value)
ColorIndex is a Property, not an Object. As such, ColorIndex.Value will return an error. Note that you haven't included the .Value when testing in the Immediate Window, and it works as expected:
?ws.Cells(j, i).DisplayFormat.Interior.ColourIndex 'This will work
?ws.Cells(j, i).DisplayFormat.Interior.ColourIndex.Value 'This will err
Also, there is no need for you to put it in brackets, either:
cond = ws.Cells(j, i).DisplayFormat.Interior.ColourIndex
Ans: I was writing Colour instead of Color.
i'm new with VBA and i'm currently working on creating an evaluation form for one of our LOBs. I'm having a hard time understanding what is wrong with my current code wherein it would not divide the value of two text boxes. when i tried to divide the value of one text box to a number it would work. however that is not what i'm looking for since the value in the text boxes are dependent on the form questions (there are questions that are NA).
I have tried the code below and its not working.
Sub CusImp2_div()
CusImp2.Value = Val(CusImp1.Value) / Val(CusImp3.Value)
CusImp2.Value = Format(Me.CusImp2.Value, "0.00%")
End Sub
the source of the values are...
Sub custotal_mulcal()
Me.CusImp1.Value = Val(CustTotal1.Value) * (0.33)
Me.CusImp1.Value = Application.WorksheetFunction.Round(Val(CusImp1.Value), 2)
Me.CusImp3.Value = Val(CustTotal2.Value) * (0.33)
Me.CusImp3.Value = Application.WorksheetFunction.Round(Val(CusImp3.Value), 2)
End Sub
when i run the formula and activate the userform i'm experiencing a debug problem and i can't seem to figure out what to do.
i expect the output to be a percentage of the output ex. 96%
i really hope that someone can help me with this and i'm actually frustrated because im runnning after a deadline.
thank you!
'I think I found the answer to this question. I found the formula below in Youtube and the form is working well now. The only limitation though is that the percentage would not change even though I tried to change my answers (I will look into how I can work around this one)..
Sub CusImp2_div()
Dim a As Double
Dim b As Double
Dim answer As Double
a = CusImp1.Value
b = CusImp3.Value
answer = a / b
If b <> 0 Then
answer = a / b
End If
Me.CusImp2.Value = answer
Me.CusImp2.Value = Format(Me.CusImp2.Value, "0.00%")
End Sub
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.
Quick question that should be easy enough for a lot of you but I'm not well versed in VBA or code in general for that matter but I have a problem that only a Macro or piece of VBA code can resolve for me. I have to edit a large number of data entries in a spreadsheet, cell by cell.
So on to the question. Could you please show me an example or provide a complete macro for me to use to edit these cells?
The editing that I require is as follows:
I need to read each cell in the following range: B2 to Q383. A typical entry that needs to be examined and edited looks like this: 629.64\3.00\01:30
What needs to happen now is for everything to the left of the first "\" and everything to the right of the second "\" needs to be removed, including the "\", from each cell.
I've tried fiddling around with the LEFT and RIGHT commands and I can output the data that needs to be removed from the cells with something like this
=left(B11, Find("\", B11) - 1)
So what would be the delete command in a macro to target that data selection in that cell? Or how do I use a delete command with those parameters?
Thanks in advance for any advice or answers!
Not 100% sure what you're after - you say you want to remove the bits from the left and right, but the formula returns the bit on the left.
Anyway, here's 3 formula to do it:
Left: =TRIM(LEFT(B11,FIND("\",B11)-1))
Middle: =LEFT(MID(B11,FIND("\",B11)+1,LEN(B11)),FIND("\",MID(B11,FIND("\",B11)+1,LEN(B11)))-1)
Right: =MID(B11,FIND("\",SUBSTITUTE(B11,"\","~",1))+1,LEN(B11))
And three VBA functions to do it
(use these as you would formula - =leftbit(B11), or if you're looking for something other than backslashes - =leftbit(B11,"|") will find the I-bar as a divider. )
Public Function LeftBit(target As Range, Optional Divider As String = "\") As String
LeftBit = Trim(Left(target, InStr(target, Divider) - 1))
End Function
Public Function MiddleBit(target As Range, Optional Divider As String = "\") As String
Dim First As Long, Second As Long
First = InStr(target, Divider)
Second = InStr(First + 1, target, Divider)
MiddleBit = Mid(target, First + 1, Second - First - 1)
End Function
Public Function RightBit(target As Range, Optional Divider As String = "\") As String
RightBit = Right(target, Len(target) - InStrRev(target, Divider))
End Function