How to run a macro in a selection of cells

kanachan

New Member
Joined
Aug 30, 2024
Messages
10
Office Version
  1. 2016
Platform
  1. Windows
Hello!
I've created a macro and I would like to run it easily in each cell from a selection of cells (let's say, for example, 100, 1000, 10000 cells of a certain row or column).

I thought by selecting with the mouse or the keyboard all the cells in which I want to run the macro, and running it, I would get it, but what happens is that the macro is run in the first cell and then, the result of running the macro in that first cell is pasted in the rest of cells, whereas what I would like is the macro run in each one of the cells from the selection (giving as a consequence a different result in each cell). How could I do it?

Thank you very much in advance for all your help.
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
If you want to run your code against the cells in your selection, you can loop through that range in VBA structured like this:
VBA Code:
Dim cell as Range
For Each cell in Selection
    ...
Next cell
However, based on how you have written your code, it may need to be edited to make it dynamic (if you have hard-coded range references in there).
We would need to see your code in order to determine that.
 
Upvote 0
@Joe4
Thank you very much for your answer. :)
The macro that I would like to run on each and every cell in my selection is located in the VBA editor in Module1. The code you have put in your answer, I suppose I should paste it in a separate module, let's say Module2, right?

And what should I put in place of the ellipses? Maybe the following?

Application.Run "'[name of the file].xlsm'![name of the macro]"

Sorry for asking these questions that may be silly. I have no programming knowledge and right now I am learning as I go. Sorry for the trouble.
 
Upvote 0
So much of this depends on what your code does and how it is written. If it has hard-coded range references in it, it will override the loop and just keep updating the same few cells multiple times.
We may need to edit your code to make it dynamic so it runs on each cell in your selection.

Can you please post the VBA procedure that you want to make these changes to?
See this post on how to post your VBA code in a way that is easy for us to read and copy: How to Post Your VBA Code
 
Upvote 0
The code I want to run in each cell of the selection is this one:

VBA Code:
'References required
'Microsoft HTML Object Library
'Microsoft Internet Controls

Option Explicit

#If VBA7 Then
    Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If


Public Sub Convert_Japanese_Words()

    With ThisWorkbook.ActiveSheet
        Selection.Value = Convert_Word(ActiveCell.Text)
    End With
    
End Sub


Public Function Convert_Word(word As String) As String

    Dim URL As String
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim button As HTMLButtonElement
    Dim textInput As HTMLTextAreaElement
    Dim katakanaCheckbox As HTMLInputElement
    Dim resultText As HTMLDivElement
    Dim timeout As Date
    
    URL = "https://www.jcinfo.net/ja/tools/kana"
    
    Set IE = Get_IE_Window(URL)
    If IE Is Nothing Then Set IE = Get_IE_Window("")
    
    If IE Is Nothing Then
        Set IE = New InternetExplorer
        IE.Visible = True
        IE.navigate URL
        While IE.Busy: DoEvents: Sleep 20: Wend
    
        Set HTMLdoc = IE.document
        
        'Click cookies Consent button, if present
        '<button class="fc-button fc-cta-consent fc-primary-button" role="button" aria-label="Consent" tabindex="0">
        ' <div class="fc-button-background"></div>
        ' <p class="fc-button-label">Consent</p>
        '</button>
        
        timeout = DateAdd("s", 5, Now)
        On Error Resume Next
        Do
            Set button = HTMLdoc.querySelector("button.fc-button.fc-cta-consent.fc-primary-button")
            DoEvents
            Sleep 20
        Loop While button Is Nothing And Now <= timeout
        On Error GoTo 0
        If Not button Is Nothing Then button.Click
    
    End If
    
    Set HTMLdoc = IE.document
    
    'Put word in text area
    '<textarea name="text" id="input_text" placeholder="?????????????" lang="ja" class="form-control">??????</textarea>
    
    Set textInput = HTMLdoc.getElementById("input_text")
    textInput.Value = word
    
    'Ensure the 'Include katakana' checkbox is ticked
    '<div class="custom-control custom-checkbox">
    ' <input id="is_katakana" class="custom-control-input" name="is_katakana" type="checkbox" value="1">
    '  <label class="custom-control-label" for="is_katakana" id="is_katakana">
    '   ????????
    '  </label>
    '</div>
  
    Set katakanaCheckbox = HTMLdoc.getElementById("is_katakana")
    If Not katakanaCheckbox.Checked Then katakanaCheckbox.Click
    
    'Click the 'Furigana conversion" button
    '<button type="submit" class="btn btn-primary">??????</button>
    
    Set button = HTMLdoc.querySelector("button.btn.btn-primary")
    button.Click
    
    While IE.Busy: DoEvents: Sleep 20: Wend
    While HTMLdoc.readyState = "loading": DoEvents: Sleep 20: Wend
    
    'Extract result from 3rd text box
    '<div class="_result my-5 p-2" lang="ja">
    ' <div class="line">
    '  <span class="morpheme">?</span>
    '  <span class="morpheme">?</span>
    '  <span class="morpheme">?</span>
    '  <span class="morpheme">?</span>
    ' </div>
    '</div>
    
    Dim results As IHTMLDOMChildrenCollection
    Do
        Set results = HTMLdoc.querySelectorAll("div._result.my-5.p-2")
                If HTMLdoc.querySelectorAll("div._result.my-5.p-2") = Error Then
                Convert_Word = MsgBox Msg & Msg = "error"
                End If
        DoEvents
        Sleep 20
    Loop Until results.Length = 3
  
    Convert_Word = results(2).innerText
    
End Function


Private Function Get_IE_Window(partialURLorName As String) As InternetExplorer

    'Look for an IE browser window or tab already open at the (partial) URL or location name and, if found, return
    'that browser as an InternetExplorer object.  Otherwise return Nothing

    Dim Shell As Object
    Dim IE As InternetExplorer
    Dim i As Variant 'Must be a Variant to index Shell.Windows.Item() array
    
    Set Shell = CreateObject("Shell.Application")
    
    i = 0
    Set Get_IE_Window = Nothing
    While i < Shell.Windows.Count And Get_IE_Window Is Nothing
        Set IE = Shell.Windows.Item(i)
        If Not IE Is Nothing Then
            If IE.Name = "Internet Explorer" And InStr(IE.LocationURL, "file://") <> 1 Then
                If InStr(1, IE.LocationURL, partialURLorName, vbTextCompare) > 0 Or InStr(1, IE.LocationName, partialURLorName, vbTextCompare) > 0 Then
                    Set Get_IE_Window = IE
                End If
            End If
        End If
        i = i + 1
    Wend
    
End Function

This code is a modification of the original code created by @John_w in this previous topic I asked: How to convert a column of Japanese words in a column of Hiragana words in Excel

Anything wrong in the code is my fault. The original code is correct, but I've tried to modify it by searching on Google and taking a shot in the dark to adapt it to new and sudden project requirements, that is

1) to make the running of the macro faster (I reduced Sleep from 100 to 20, but I don't see much difference)

2) to adapt it to just a selection of cells (regardless of size of the selection) instead of a whole column, and replace the word sent to ふりがな振りツール | JCinfo.net for the result contained in the third result textbox.

3) if a word sent to the website ふりがな振りツール | JCinfo.net returns an error, like this one, 嚙む, replace the word sent to the website for a message of error.

If possible, could you or someone please check the code so that there's nothing mistaken? I'm very sorry for asking this. I've done the modifications following Microsoft and other sites instructions, but I'm completely lost about if I did them correctly.
 
Upvote 0
So, it looks like you want to use the "Convert_Word" function to convert the words in their own cells.

If that is the case, as long as that function exists in the same workbook, you can do this:
VBA Code:
Dim cell as Range
For Each cell in Selection
    cell.Value = Convert_Word(cell.Text)
Next cell
 
Upvote 1
Solution
@Joe4

Thank you so much, Joe, for your reply!

I'm so sorry I didn't get back to you sooner. The changes I made to the Convert_Word function weren't quite right, so I've been tinkering with it here and there until I've gotten it to work somehow, so I can then test the function you posted.

Your function was trouble-free and worked perfectly, which I'd like to thank you for once again. Thank you very much. :)
 
Upvote 0
You are welcome.
Glad I was able to help!
 
Upvote 1

Forum statistics

Threads
1,221,417
Messages
6,159,789
Members
451,589
Latest member
Harold14

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top