我试图将范围中第一个单元格的前7个字符设置为命名范围名称,如果单元格以单词“kit”开头。
这是我到目前为止所做的:
Sub DefineRanges()
Dim rngStart As Range
Set rngStart = Range("A1")
Dim LastRow As Integer
Dim RangeName As String
For Each cell In Range("A2:A7")
If LCase(Left(cell.Value, 3)) = "kit" Then
RangeName = LCase(Left(cell.Value, 7))
ActiveWorkbook.Names.Add _
Name:=RangeName, _
RefersToLocal:=Range(rngStart.Address & ":C" & cell.Row - 1)
Set rngStart = Range("A" & cell.Row)
End If
LastRow = cell.Row
Next
RangeName = LCase(Left(cell.Value, 7))
ActiveWorkbook.Names.Add _
Name:=RangeName, _
RefersToLocal:=Range(rngStart.Address & ":C" & LastRow)
End Sub
基本上我希望它能够查看我的整个范围,找到以“kit”开头的任何单元格,创建一个从该单元格开始到下一个以“kit”开头的单元格的命名范围,并指定第一个该单元格的7个字符作为范围名称。到目前为止,我能够创建范围,但是当我尝试将单元格的内容传递到范围名称时,我遇到了问题。有什么想法吗?
答案 0 :(得分:2)
这假设您的数据与上一个问题类似。
它使用Match查找每个"Kit..."
,保存几次迭代:
Sub DefineRanges()
Dim rngStart As Long
Dim RangeName As String
Dim col As Long
Dim PreFx As String
col = 1 'change to the column number you need
PreFx = "kat" 'change to the prefix you are looking for
With Worksheets("Sheet7") 'change to your sheet
On Error Resume Next
rngStart = Application.WorksheetFunction.Match(PreFx & "*", .Columns(col), 0)
On Error GoTo 0
If rngStart > 0 Then
Do
i = 0
On Error Resume Next
i = Application.WorksheetFunction.Match(PreFx & "*", .Range(.Cells(rngStart + 1, col), .Cells(.Rows.Count, col)), 0) + rngStart
On Error GoTo 0
If i > 0 Then
RangeName = LCase(Left(.Cells(rngStart, col).Value, 7))
ActiveWorkbook.names.Add name:=RangeName, RefersToLocal:=.Range(.Cells(rngStart, col), .Cells(i - 1, col + 2))
rngStart = i
Else 'no more "kit..." so find the last row with data and use that
i = Application.WorksheetFunction.Match("zzz", .Columns(col))
RangeName = LCase(Left(.Cells(rngStart, 1).Value, 7))
ActiveWorkbook.names.Add name:=RangeName, RefersToLocal:=.Range(.Cells(rngStart, col), .Cells(i - 1, col + 2))
End If
Loop While i < Application.WorksheetFunction.Match("zzz", .Columns(col))
End If
End With
End Sub