How can I use square brackets in Application.OnKey? (Excel VBA) - vba

I would like to use the key combination Shift + Alt + [ to call a subroutine in my VBA project. Here is the code I have tried:
Appication.OnKey "+%[", "mySubroutine"
I have had no problems using other characters with shift and alt, such as lowercase letters and numbers. However, when I try to use the left square bracket, I get the following error:
Method 'OnKey' of object '_Application' failed
I have also tried to use the left square bracket with all of the different combinations Ctrl, Alt, and Shift. They all produce the same error.
Application.OnKey "^[", "mySubroutine"
Application.OnKey "+[", "mySubroutine"
Application.OnKey "%[", "mySubroutine"
Application.OnKey "^+[", "mySubroutine"
Application.OnKey "^%[", "mySubroutine"
Application.OnKey "^+%[", "mySubroutine"
I also tried using the ASCII code for the left square bracket (91) like this:
Application.OnKey "+%{91}", "mySubroutine"
with no luck.
I also tried using Excel's built-in Chr() function with that ASCII keycode:
Application.OnKey "+%" & Chr(91), "mySubroutine"
which did not work, either.
I am running Excel 2013. Another computer in our office is running Excel 2003, and though that computer is using Excel4Macro language, it IS able to use the left square bracket to set up a keyboard shortcut.
It seems like Microsoft removed this capability in the newer version of Excel. However, if anyone can figure out a way to make it work, I would be grateful!

Application.OnKey "+%{[}", "mySubroutine"
Same codes as for SendKeys...
How to print or send braces ( ) using VBA sendkeys
https://social.technet.microsoft.com/wiki/contents/articles/5169.vbscript-sendkeys-method.aspx
The plus sign "+", caret "^", percent sign "%", tilde "~", and
parentheses "()" all have special meanings and must be enclosed within
braces "{}". Square brackets "[]" must also be enclosed within braces
although they have no special meaning. To specify brace characters
themselves, use "{{}" and "{}}".

Related

How do you use " (double quotes) in a formula in OpenOffice VBA? For instance with Replace()

I am looking to replace double quotes, ", with backslash escaped double quotes - \".
I read online that you can use double quotes in VBA, if you use two double quotes inside the main double quotes. But, this didn't seem to work for me. For instance I tried the following code:
Function ADDSLASHES(InputString As String)
NewString = Replace(InputString, "\", "\\")
NewString = Replace(NewString, "'", "\'")
NewString = Replace(NewString, """", "\""")
ADDSLASHES = NewString
End Function
When I tested it, this function successfully substituted the single backslash and the single quotes, but not the doule quotes.
I also read that you can use CHR(34), and elsewhere to use CHR(147). But this too didn't work. I tried the following lines:
NewString = Replace(NewString, CHR(34), "\"+CHR(34))
NewString = Replace(NewString, CHR(147), "\"+CHR(147))
But testing it out with a cell that had double quotes did not work. Am I doing something wrong? How might I use double quotes with the Replace() function?
When I entered a"b in a cell, Calc converted it to a right double quote, not a left one. Adding this line made it work:
NewString = Replace(NewString, CHR(148), "\"+CHR(148))
Be aware that x94 (decimal 148) is an extended ASCII encoded character, which is something I would avoid at all costs. It's strongly recommended to only use the first 128 characters as ASCII and to use Unicode for everything else.
The Unicode value for a right double quotation mark is U+201D. Sadly, apparently LibreOffice Basic does not have a native way to work with such values. There is ChrW but that requires the VBA compatibility option. Another method is to call the UNICODE() spreadsheet function from Basic, but that is cumbersome.
My preference: Don't use Basic for anything important. LibreOffice macros can be written in Python instead, which has strong Unicode support.
EDIT:
One thing I forgot to mention yesterday: Select a quotation mark in the formula bar and press Alt+x to find out what it really is. This will convert it to the Unicode value and then back again.
EDIT 2:
That's correct—Alt+X only works in LibreOffice, not AOO. Also for some reason, the extended ASCII code above doesn't seem to work in AOO. Maybe that's not a bad thing. Anyway, here is the Unicode spreadsheet function access approach, and it works for me in both AOO and LO.
fa = createUnoService("com.sun.star.sheet.FunctionAccess")
ch = fa.CallFunction("UNICHAR", Array(CLng("&H201D"))
NewString = Replace(NewString, ch, "\"+ch)
If this doesn't work, then you probably have something else in the cell. To figure out what it is, you could install LibreOffice. Or there are lots of other ways; most often I use GVim text editor. Also I just now googled and found https://www.branah.com/unicode-converter where you can paste some text and see the actual UTF-16 hexadecimal values.

How to add multiple words to one line of command

I'm trying to run a function. When you hit the button if the textbox includes the following words below it will display "Please don't swear." The problem is that I'm trying to add multiples words to one line of command using the "or" function.
For some reason it does not work. Here is my code:
If InStr(1, Command.Text, "shit" Or "ass", vbTextCompare) Then
MsgBox("Please don't swear.")
Any help is appreciated! :)
We're not in VB6 anymore Toto. Let's not use InStr or MsgBox.
Dim prohibitedWords = {"bad", "word"}
If prohibitedWords.Any(Function(s) TextBox1.Text.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) <> -1) Then
'...
End If
I used IndexOf rather than Contains there to allow a case-insensitive comparison.
One issue with that is that is will match parts of other legitimate words. To avoid that, you should probably use a Regex and match whole words only. I'll leave it to you to search how to do that.

Range accepts sometimes only semicolons instead of commas

I have reduced my problem to the following code example. I am using a German Excel version in which separators in normal Excel formulas are semicolons ";" instead of "," (e.g. =SUMME(A1;A3) instead of =SUM(A1,A3)).
Now the code which works different from time to time:
Sub CommasDoNotWorkAnymore()
Dim a()
Dim i%
a = Array("A1,A3,A5", "B1", "B2")
i = 0
Debug.Print Sheets(1).Range(a(i)).Address
End Sub
Normally, when starting Excel, this code works. But sometimes Excel seem to switch the accepted separators used in the Range() to semicolons untill I restart Excel. This occurs most times when rerunning the code after a runtime error.
Is this a general Excel bug? Does anybody know what is behind this behaviour? Is there some Excel-wide "local option" for the Range class?
EDIT: I just tried to convert the a(i) with CStr(a(i) but this does also not work. So no ByRef kind of problem...
If you want to control it, check first what separator is currently in use. What I guess is that you want to know the list separator:
Application.International(xlListSeparator)
Check other separators here:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-international-property-excel
The other time I had a problem with identifying decimal separator in VBA. Finnally I was able to get it in this way:
Function GetVBAdecimalSep()
Dim a(0) As Variant
a(0) = 1 / 2
GetVBAdecimalSep = Mid(a(0), 2, 1)
End Function
Changing separator not always works. Please see this: Changing decimal separator in VBA (not only in Excel)
The best solution is to check/change locale, even temporary.
Application.LanguageSettings.LanguageID(msoLanguageIDUI)
gives the LCID which would be 1033 for English (US)

How to send a right curly bracket with Dragon NaturallySpeaking's advanced scripting?

How to send a right curly bracket (i.e., }) with Dragon NaturallySpeaking's advanced scripting?
MSDN's document on the SendKeys Statement says:
To specify brace characters, use {{} and {}}.
Sending a left curly bracket (i.e., {), works fine with the following advanced scripting command:
Sub Main
SendKeys "{{}"
End Sub
However, when I try to do the same for the right curly bracket (i.e., }), it doesn't work:
Sub Main
SendKeys "{}}"
End Sub
Why?
This is an old glitch in Advanced Scripting.
You can use the ASCII code instead:
Sub Main
SendKeys Chr(125), True
End Sub
You don't need to escape a right brace by itself, just do:
SendKeys "}"
But if you want to send a whole "braced" expression, it gets more complicated. For example, to use a script to send "{Esc}" you need this:
SendKeys "{{}Esc}" ' {Esc}
Hth,
One inconvenient way to circumvent this issue: going through the clipboard, as shown below.
Sub Main
originalClipboard = Clipboard
Clipboard("{")
SendKeys "^v"
Wait(0.2)
Clipboard(originalClipboard)
End Sub

Programming a Japanese keyboard "Henkan" 「変換」 button

I am programming VBA(7.0) in Excel 2010 and am trying to make a macro that will change a string variable (containing Kanji) into it's Hiragana constituents. As far as I could tell there are no VBA-specific methods to do this. Hence, I assume the way to go about it, is to attempt to emulate the [henkan] 「変換」 button on a Japanese Keyboard.
For those not accustomed to Japanese Keyboards, the 「変換」 button is used to change constituent Hiragana as it is written, into a Kanji compound (likewise highlighting existing text and pressing it will offer options to change it to other Kanji as well as it's constituent Hiragana or Katakana). Pressing the button will bring up a list from the IME which lists possible selections for your entry.
I gathered from here and here that the scancode of the button in question is 79.
Putting 1 + 1 together (getting 3) and trying the code below didn't yield any results.
Private Sub test_Click()
Sheets("Main").Range("A1").Select '<--- A1 contains a Kanji Compound
Application.SendKeys (79) '<--- Both (79) and ("79") were tried
End Sub
I noticed there are the following VBA functions (which may end up helping with an end result) but they don't seem to help the situation.
StrConv (Can convert Hiragana <> Katakana, but not Kanji)
Phonetics
.Add (Can add the reading of the Kanji (as Furigana) however this requires user input and is not automatic).
.CharacterType (Returns or sets the phonetics type; Hiragana, Katakana etc.)
IME (Largely used to set input rules)
A co-worker suggested that I may need to look at the IME API to see firstly, if I can access it (permissions with the API), and secondly if it will let me know the way of accessing the key. However my experience with API'S (especially IME) is nil to none.
Is there a VBA-specific way of emulating the Kanji -> Hiragana Process (only a one way Kanji to Hiragana conversion is required)?
Failing that, is there a process which could sendkey the「変換」 button and select the Hiragana option?
Although I don't like to answer my own questions, I have found a solution.
In order to get the Excel [PHONETIC] function to work properly, [Japanese Editing Tools] must be installed. These are found in either a Language Pack (which for Excel 2010 is USD$25 each) or by installing from a Japanese Language Microsoft Office [2010] installation disk - Just installing the tools to an English Office edition is possible (thus mitigating the need for a full Japanese edition installation).
Failure to install the [Japanese Editing Tools] will mean that the [PHONETIC] function will ALWAYS contain a blank string (unless syntactically incorrect) for both the in-cell and VBA functions.
The full steps are as follows.
Install Microsoft Office Japanese Editing Tools for your edition of Microsoft Office (MO2010 > Install JET MO2010 edition)
Use the [PHONETIC] Function.
This can be used as an in-cell function with the format
=Phonetic(reference)
Where [reference] is the name of a cell ie.[A2] - You can NOT directly input a string into this in-cell function).
In VBA the function is Application.GetPhonetic(text)
Where [text] is either directly inputted, a string variable or a reference to a cell with a string.
Assuming automated Hiragana is required as Kanji is entered into a Userform Textbox.
Kanji Input TextBox => [KanjiBox], Hiragana Reading TextBox => [YomiBox]
Private Sub KanjiBox_Change()
'Finds last entry in Range (for this example, range is in the [B] column)
lastEntry = Sheets("Entries").Range("B1048576").End(xlUp).Row
'Finds if entry already exists in range, if it does;_
launches MsgBox Warning and clears all fields. Range starts from Row 7.
For entryRow = 7 To lastEntry
If KanjiBox = Sheets("Entries").Range("B" & entryRow) Then
MsgBox "There is already an entry for " & KanjiBox
KanjiBox = ""
YomiBox = ""
Exit For
End If
Next entryRow
'This sets the [YomiBox] as a Hiragana reading of the Kanji_
(Uses StrConv to change the Phonetic result from Katakana to Hiragana)
YomiBox = StrConv(Application.GetPhonetic(KanjiBox), vbHiragana)
'The following fixes leftover reading text when backspacing
If KanjiBox = "" Then
YomiBox = ""
End If
End Sub
Using this method, 「変換」 key emulation was not required.
Any way of Emulating the 「変換」 key as a key press event, without the use of third party applications is still, as yet, unknown by me.