excel 循环来唯一地命名区域中的每个非空单元格

hyrbngr7  于 2023-02-05  发布在  其他
关注(0)|答案(2)|浏览(171)

下面的代码命名范围中的最后一个单元格,而不是命名范围中的每个单元格。
我尝试运行这个循环,以便从单元格A1开始,将任何非空单元格命名为“Guidance1”、“Guidance2”,依此类推。

Sub GiveAllCellsNames()

    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim R As Range
    Dim NameX As String

    Static I As Long
    I = I + 1
 
    NameX = "Guidance" & I

    For Each R In Range("A1:A390").Cells
        If R.Value <> "" Then
            With R
                wb.Names.Add NameX, RefersTo:=R
            End With
        End If
    Next R

End Sub

我尝试了这个循环,但没有在“R”范围变量上使用“with语句”,得到了相同的结果。

jqjz2hbq

jqjz2hbq1#

可以使用Range对象的name属性添加命名范围。
变更

wb.Names.Add NameX, RefersTo:=R

R.Name = NameX

I需要递增,并且名称应在循环内更新。

Sub GiveAllCellsNames()

    Dim wb As Workbook

    Set wb = ActiveWorkbook

    Dim R As Range

    Dim NameX As String

    Static I As Long

    For Each R In Range("A1:A390").Cells

        If R.Value <> "" Then
        
            I = I + 1
            NameX = "Guidance" & I
            
            With R

                wb.Names.Add NameX, RefersTo:=R

            End With

        End If

    Next R

End Sub
p4rjhz4m

p4rjhz4m2#

命名非空单元格

Sub NameAllCells()

    Const BeginsWithString As String = "Guidance"

    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
    Dim rg As Range: Set rg = ws.Range("A1:A390")
    Dim Data() As Variant: Data = rg.Value
    
    DeleteNamesBeginsWith wb, BeginsWithString
    
    Dim r As Long
    Dim n As Long
    
    For r = 1 To UBound(Data, 1)
        If Len(CStr(Data(r, 1))) > 0 Then
            n = n + 1
            wb.Names.Add BeginsWithString & n, rg.Cells(r)
        End If
    Next r

End Sub

Sub DeleteNamesBeginsWith( _
        ByVal wb As Workbook, _
        ByVal BeginsWithString As String)
    
    Dim nmLen As Long: nmLen = Len(BeginsWithString)
    
    Dim nm As Name
    
    For Each nm In wb.Names
        If InStr(1, nm.Name, BeginsWithString, vbTextCompare) = 1 Then nm.Delete
    Next nm
    
End Sub

相关问题