简体   繁体   中英

VBA Pull Work Sheet Names into a Delimited String

Very Easy Task Here. I have a macro that drafts up an email. For the.HtmlBody field I would like it to display all of the names of the worksheets in my current workbook in the following way in the email body.

Apples

Pears

Oranges

Grapes

Bananas

The following code will populate the body of my email with as: ApplesPearsOrangesGrapesBananas

all in one line.

My full code is not shown in its entirely because some of the hard coded lines contain confidential info.

Dim wks As Worksheet, strName As String

For Each wks In Worksheets
 strName = strName & wks.Name

Next

 msg = strName
 .HTMLBody = strName

Any help is great thanks

List Worksheet Names

  • You could use the following function:
Function ListWorksheetNames( _
    ByVal wb As Workbook, _
    ByVal Delimiter As String) _
As String
    If wb Is Nothing Then Exit Function
    If wb.Worksheets.Count = 0 Then Exit Function
    
    Dim ws As Worksheet
    Dim wsNames As String
    
    For Each ws In wb.Worksheets
        wsNames = wsNames & ws.Name & Delimiter
    Next ws
    wsNames = Left(wsNames, Len(wsNames) - Len(Delimiter)) ' remove last

    ListWorksheetNames = wsNames

End Function
  • In your code you would utilize it in the following way:

     Dim msg As String msg = ListWorksheetNames(ThisWorkbook, vbLf)

    where ThisWorkbook is the workbook containing this code.

  • If you need empty lines in between, you could use vbLf & vbLf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM