简体   繁体   中英

Assigning a constraint to a cell in excel vba

I have macro enabled spreadsheet (Form) in excel, which has vba code part, where it automatically generates unique identifier, as following: It takes CSS-2020-08- text and adds a unique ID (SurveyCode) to each record of the Form (see code below):

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim IDMaxSuffix As Long, i As Long
    Dim a As Variant

    Const IDPrefix As String = "CSS-2020-08-"    '<- Edit as you want
           
    If Not Intersect(Target, Range("Table1")) Is Nothing Then

        With Range("Table1[SurveyCode]")

            a = .Value

            For i = 1 To UBound(a)

                If a(i, 1) Like "*-######" Then

                    If Right(a(i, 1), 6) > IDMaxSuffix Then IDMaxSuffix = Right(a(i, 1), 6)

                End If

            Next i

            For i = 1 To UBound(a)

                If Len(a(i, 1)) = 0 Then

                    IDMaxSuffix = IDMaxSuffix + 1
                    a(i, 1) = IDPrefix & Format(IDMaxSuffix, "000000")

                End If

            Next i

            Application.EnableEvents = False
            .Value = a
            Application.EnableEvents = True

        End With

    End If

End Sub

In the "Config" sheet of my excel Form, I want to write that text in B4 cell - CSS-2020-08-, as following:

在此处输入图片说明

And, finally, to modify the above code, so, that instead of

 Const IDPrefix As String = "CSS-2020-08-"

in the upper part of the code, it would referenced to my B4 cell of Config sheet!

Is it possible to modify this code - to reference to a B4 cell of a Config sheet, instead of just having "CSS-2020-08-" text inside VBA code?

Replace...

Const IDPrefix As String = "CSS-2020-08-"   '<- Edit as you want

With...

Dim IDPrefix As String: IDPrefix = ThisWorkbook.Sheets("Config").Range("B4")

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