In VB or C# using Microsoft.Office.Interop.Excel how do I do the following?
I have an excel sheet with names assigned to each cell and I'm trying to get a list of cells where the name contains a certain substring. Maybe something like this:
worksheet.Cells.Where(x => x.Name.Contains("_"));
I can't figure out how to do this since worksheet.Cells is a range and not a collection. Is there a way to achieve this?
In VBA, you can iterate through the Names collection. All of the Names are a property of the Workbook collection; in addition, those Names with a worksheet scope, will also be in that Worksheet Names Collection.
So to return a list, depending on what you want to do with the list, one method is with a User Defined Function:
Option Explicit
Function GetNames(sContains As String) As Variant
Dim WB As Workbook
Dim N As Name, NS As Names
Dim colNames As Collection
Dim V() As Variant
Dim I As Long
Set WB = ThisWorkbook
Set NS = WB.Names
Set colNames = New Collection
ReDim V(0 To 1)
For Each N In NS
If N Like "*" & sContains & "*" Then
V(0) = N.Name
V(1) = N.RefersTo
colNames.Add V
End If
Next N
ReDim V(1 To colNames.Count, 1 To 2)
For I = 1 To colNames.Count
V(I, 1) = colNames(I)(0)
V(I, 2) = colNames(I)(1)
Next I
GetNames = V
End Function
I had to solve a similar problem once and used:
currentFind is a ExcelRange.
currentFind = mySheet.UsedRange.Find("_", misvalue,
Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
misvalue, misvalue);
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.