+ Reply to Thread
Results 1 to 9 of 9

Make a function out of a part of VBA Script

Hybrid View

  1. #1
    Registered User
    Join Date
    01-21-2025
    Location
    Italy
    MS-Off Ver
    2016
    Posts
    8

    Make a function out of a part of VBA Script

    Hi there,

    In one of my macros, there a part which I need several times. Until now, this part is copy pasted in the code everytime it is needed. This is not very elegant. Here the code we talk about, it's about looking up specific words in an Excel sheet and spitting out in which column they are:

    ' Variables
    Dim Words As Variant
    Dim WordsRange As Excel.Range
    Dim i As Integer
    
    ' define search terms
    Words = Array("Input 1", "Input 2", "Input 3")
    
    ' Look for each input
    For i = LBound(Words) To UBound(Words)
        Dim WordsRange As Excel.Range
        Set WordsRange = xlWS.Cells.Find(Words(i), LookIn:=xlValues, LookAt:=xlWhole)
    
        If Not WordsRange Is Nothing Then
            WordsColumn = ConvertToLetter(WordsRange.Cells.Column)
            Exit For
        End If
    Next i
    (note: "ConvertToLetter" is another function, converting the number of the column into the corresponding letter - column 1 = A and so on. This function works fine)
    I tried like this, basically wrapping the whole block around a Function:

    Function SearchWords(Words As Variant) As String
    
    'define search terms
    Dim WordsRange As Excel.Range
    Dim WordsColumn As Integer
    Dim i As Integer
    
    ' Look for each input
    For i = LBound(Words) To UBound(Words)
        Set WordsRange = xlWS.Cells.Find(Words(i), LookIn:=xlValues, LookAt:=xlWhole)
        If Not WordsRange Is Nothing Then
            WordsColumn = ConvertToLetter(WordsRange.Cells.Column)
            Exit For
        End If
    Next i
    
    End Function
    But this gives an error (424) on the line
    Set WordsRange = xlWS.Cells.Find(Words(s), LookIn:=xlValues, LookAt:=xlWhole)
    Any idea how to solve this?
    Thanks a lot

  2. #2
    Forum Moderator zbor's Avatar
    Join Date
    02-10-2009
    Location
    Croatia
    MS-Off Ver
    365 ProPlus
    Posts
    16,166

    Re: Make a function out of a part of VBA Script

    Sheet name xlWS is not defined under Function.
    You need either to declare it globally or within a function
    Never use Merged Cells in Excel

  3. #3
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Make a function out of a part of VBA Script

    Or pass it as an argument:

    Function SearchWords(Words As Variant, xlWS as Worksheet) As String
    
    'define search terms
    Dim WordsRange As Excel.Range
    Dim i As Integer
    
    ' Look for each input
    For i = LBound(Words) To UBound(Words)
        Set WordsRange = xlWS.Cells.Find(Words(i), LookIn:=xlValues, LookAt:=xlWhole)
        If Not WordsRange Is Nothing Then
            SearchWords = ConvertToLetter(WordsRange.Cells.Column)
            Exit For
        End If
    Next i
    
    End Function
    Last edited by romperstomper; 02-04-2025 at 11:52 AM.
    Everyone who confuses correlation and causation ends up dead.

  4. #4
    Forum Contributor
    Join Date
    10-02-2012
    Location
    UK
    MS-Off Ver
    Office 365
    Posts
    293

    Re: Make a function out of a part of VBA Script

    I feel like everyone is misinterpreting the use of the word function in the title. Seems to me like he wants to add his macro to his personal.xlsb file so he can user this macro on multiple sheets without having to copy and paste it every time.

    Also doesn't a function require something to return?

  5. #5
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Make a function out of a part of VBA Script

    I'm not really sure how you get that interpretation from "In one of my macros, there a part which I need several times. Until now, this part is copy pasted in the code everytime it is needed". But I'm sure the OP will clarify.

  6. #6
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    O365 V2408
    Posts
    15,218

    Re: Make a function out of a part of VBA Script

    Something tells me there is more to meets the eye...
    Perhaps @blue headphones can give a bit more information about the actual use of this...I am sure there is a simplification...
    Why the need for column letter and not just column number...Why the need to use this scenario multiple times, why exiting when 1 is found...
    And why a function for column letter...
    WordsColumn = Split(Cells(1, WordsRange.Column).Address, "$")(1)
    Last edited by Sintek; 02-05-2025 at 03:53 AM.
    Good Luck...
    I don't presume to know what I am doing, however, just like you, I too started somewhere...
    One-day, One-problem at a time!!!
    If you feel I have helped, please click on the [★ Add Reputation] to left of post window...
    Also....Add a comment if you like!!!!
    And remember...Mark Thread as Solved...
    Excel Forum Rocks!!!

  7. #7
    Registered User
    Join Date
    01-21-2025
    Location
    Italy
    MS-Off Ver
    2016
    Posts
    8

    Re: Make a function out of a part of VBA Script

    Quote Originally Posted by Sintek View Post
    And why a function for column letter...
    WordsColumn = Split(Cells(1, WordsRange.Column).Address, "$")(1)
    Because I'm new to VBA and I think I make things more complicated than they are. I tried to have something that works for all columns, also after column Z :D I'll try out your suggestion as soon as I can, thank you!

    Column letter is needed because I need to read out the values in that column

    Dim lastRow As Long
    lastRow = xlWS.Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 2 To lastRow ' Loop over the column
            
        strWord1 = xlWS.Range(ColumnWord1 & i).Value ' Value in the Word 1 column
        strWord2 = xlWS.Range(ColumnWord2 & i).Value ' Value in the Word 2 column
        strWord3 = xlWS.Range(ColumnWord3 & i).Value ' Value in the Word 3 column

  8. #8
    Registered User
    Join Date
    01-21-2025
    Location
    Italy
    MS-Off Ver
    2016
    Posts
    8

    Re: Make a function out of a part of VBA Script

    Thank you for the answers!

    PrizeGotti: No, I actually only want to make my macro shorter by replacing a code block appearing several times by a function. As the macro is working correctly now (without the function), it's more about learning how to make it more efficient. You hint that a function needs something to return might show that I'm just trying to use the wrong concept for what I want to achieve.

    romperstomper, zbor: that's right, I missed that xlWS was not defined. However that's not a solution, because the worksheet needs the workbook, which in turn need the application, which needs the path. I thought passing xlWS as argument would make the trick, but there is still an error, though the number changed (error 91).
    Currently it looks like this:

    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    Dim xlWS As Excel.Worksheet
    Dim Path As Variant
    Dim fd As Office.FileDialog
    
    Dim objUndo As UndoRecord
    Set objUndo = Application.UndoRecord
    
    
    
    'Choose an Excel file. The path to the file is saved for later use.
    Set xlApp = New Excel.Application
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
        .Title = "Choose an Excel file"
        .InitialFileName = "\\path\to\the\initial\folder\"
        .Filters.Clear
        .Filters.Add "Excel files", "*.xl*"
        .AllowMultiSelect = False
        .ButtonName = "OK"
        If .Show <> -1 Then
            MsgBox "No file chosen"
            Exit Sub
        End If
    
    Path = .SelectedItems(1)
    Set xlWB = xlApp.Workbooks.Open(Path)
    Set xlWS = xlWB.Sheets(1)
    Then the macro looks for specific words in the selected Excelfile, as posted at the beginning of the thread. As there are several words to look for, this part of code is pasted around 10 times in the macro. After this process, a box is displayed, indicating in which column the words are located:

    Dim Agree As VbMsgBoxResult
    Agree = vbNo
    Do While Agree = vbNo
    
    Dim msg As String
        msg = "the following words were found" & vbNewLine & _
            "Word 1: " & ColumnWord1 & vbNewLine & _
            "Word 2: " & ColumnWord2 & vbNewLine & _
            "Word 3: " & ColumnWord3 & vbNewLine & _
            "Do you agree?"
        Agree = MsgBox(msg, vbQuestion + vbYesNoCancel, "Words and columns")
    
    If Agree = vbNo Then
            Dim WordsGroup As String
            WordsGroup = InputBox("Please select the word that is not correctly assigned" & vbNewLine & _
                                  "Word 1, Word 2, Word 3")
    
            ' Correction of column assignment
            Select Case WordsGroup
                Case "Word 1"
                    ColumnWord1 = InputBox("Please type the column for Word 1")
                Case "Word 2"
                    ColumnWord2 = InputBox("Please type the column for Word 2")
                Case "Word 3"
                    ColumnWord3 = InputBox("Please type the column for Word 3")
                End Select
            
        ElseIf Agree = vbCancel Then
            ' Clean up
            Set objMail = Nothing
            Set objOutlook = Nothing
            ' Close the Excel file
            xlWB.Close SaveChanges:=False
            xlApp.Quit
            Set xlWS = Nothing
            Set xlWB = Nothing
            Set xlApp = Nothing
            Set Path = Nothing
            Exit Sub
            
        Else ' User agrees with column assignement
            Agree = False
        End If
    Loop
    I have to say I have a bit of experience in other programing languages (Python), but VBA is very new to me. It's a process of googling, asking, copy-pasting, learning by doing I think the variable names are not 100% consistent in the example (shortened for the forum), but I hope it's still understandable.

  9. #9
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,136

    Re: Make a function out of a part of VBA Script

    Quote Originally Posted by blue headphones View Post
    I thought passing xlWS as argument would make the trick, but there is still an error, though the number changed (error 91).
    Then you did it wrong. You haven't showed us how you are actually using the function, so it's hard to comment on what you did.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. How to make a part of output of concatenate function Bold
    By skasat in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 12-21-2022, 11:07 AM
  2. How to make a part of output of concatenate function Bold
    By skasat in forum Excel Formulas & Functions
    Replies: 3
    Last Post: 12-19-2022, 12:45 PM
  3. [SOLVED] How to make part of formula take precedence over another part?
    By jordonix in forum Excel Formulas & Functions
    Replies: 3
    Last Post: 11-25-2020, 08:47 AM
  4. VBA Script to pull Model & Part numbers
    By keith81591 in forum Excel Programming / VBA / Macros
    Replies: 17
    Last Post: 09-26-2020, 01:06 PM
  5. Part of VBA script not working
    By eagleboy1234 in forum Excel General
    Replies: 0
    Last Post: 01-19-2017, 09:55 AM
  6. Excel 2003: VBA script to colour cell that contains part of text
    By garoe in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 02-15-2013, 06:22 AM
  7. [SOLVED] help with last part of script
    By RompStar in forum Excel General
    Replies: 2
    Last Post: 04-21-2005, 03:06 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1