Конечно, текст из #1 не генерирует
GUID
.
Еще несколько лет назад для генерации GUID разработчики пользовались объектом “Scriptlet.TypeLib”. Однако, после обновления Windows в 2017 году на многих компьютерах обращение к этому объекту вызывает ошибку “Run-time error ‘70’ permission denied”.
Microsoft рекомендует следующий путь (операторы Declare дополнены для совместимости с версиями до 2007):
Код |
---|
Option Explicit Private Type GUID_TYPE Data1 As Long Data2 As Integer Data3 As Integer Data4(7) As Byte End Type #If VBA7 Then Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr #Else Private Declare Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As Long Private Declare Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As Long, ByVal cbMax As Long) As Long #End If Function CreateGuidString() Dim Guid As GUID_TYPE Dim strGuid As String Dim retValue Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} retValue = CoCreateGuid(Guid) If retValue = 0 Then strGuid = String$(guidLength, vbNullChar) retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength) If retValue = guidLength Then ' valid GUID as a string CreateGuidString = strGuid End If End If End Function Sub testGuid() Debug.Print CreateGuidString() End Sub |
Do you need to generate a GUID in Excel?
GUID stands for Globally Unique Identifier, but it might also be referred to as a UUID which stands for Universally Unique Identifier. These are the same thing.
A GUID is a 32-character code consisting of both numbers and letters that are commonly used to identify items in a database.
GUIDs are generated randomly, but the probability of duplicating a randomly generated GUID is so infinitesimally small that you can be sure that it will be unique. This means there is no need for a central registry to ensure their uniqueness.
This post is going to show you how you can generate random GUIDs in Excel. Get your copy of the file used in this post and follow along!
Generate a GUID with the RANDBETWEEN Function
GUIDs are usually 128 bits long and will have the below format where the x‘s are hexadecimal digits.
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
This format organizes the 32 hexadecimal digits into groups of 8-4-4-4-12 characters. The dash character is purely for ease of reading.
A common way to generate these random hex digits in the GUIDs is to generate random decimal numbers and convert them into hexadecimal.
= RANDBETWEEN ( min, max )
This can be achieved using the RANDBETWEEN function in Excel. This function allows you to generate a random integer number between a given upper min
and lower max
bound.
= DEC2HEX ( number, [digits] )
The DEC2HEX function will convert any decimal number
to its equivalent hexadecimal representation. It also allows you to specify the number of digits
to return. This way you can always return an 8 or 4 character length hexadecimal.
= DEC2HEX ( RANDBETWEEN ( 0, 4294967295 ), 8 )
A random sequence of 8 hex digits can be generated by generating a random number between 0 and 4,294,967,295 and converting the result to a hex value using the DEC2HEX function in Excel.
= DEC2HEX ( RANDBETWEEN ( 0, 65535), 4 )
Similarly, a random sequence of 4 hex digits can be generated by generating a random number between 0 and 65535 and converting it to hexadecimal.
Then you can generate a sequence of 12 hex digits by combining an 8 and 4 sequence.
=LOWER(CONCATENATE(
DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",
DEC2HEX(RANDBETWEEN(0,65535),4),"-",
DEC2HEX(RANDBETWEEN(0,65535),4),"-",
DEC2HEX(RANDBETWEEN(0,65535),4),"-",
DEC2HEX(RANDBETWEEN(0,4294967295),8),
DEC2HEX(RANDBETWEEN(0,65535),4)
))
The above formula will generate the full GUID value including the joining dash characters.
The CONCATENATE function joins all the hex values together along with the dash to create the full GUID.
The LOWER function can also be used in the formula to create a GUID that returns lowercase instead of uppercase letters.
📝 Note: The RANDBETWEEN function is volatile so this will recalculate any time you edit the spreadsheet. You can force the recalculation and generate a new GUID by pressing the F9 key.
Generate a GUID with the WEBSERVICE Function
WEBSERVICE is a very interesting function. It allows you to call a web address and return data from that address.
When combined with a service such as uuidtools, the WEBSERVICE function will give you the ability to create your GUIDs.
https://www.uuidtools.com/api/generate/v4/count/5
The uuidtools online GUID generator is a free API you can use to generate GUIDs and UUIDs. The above URL will return a list of 5 generated GUIDs. You can change the 5 in the URL to any number you like.
= WEBSERVICE ( "https://www.uuidtools.com/api/generate/v4/count/5" )
The above formula will return a list of GUIDs.
["736f07e7-12e1-4d9f-aa83-762916761eba","c516d5f6-f816-448c-a2f7-dcb308c02393","04ce3d1b-d4f0-4c41-88cd-b90f7deacde4","960445e7-4e04-4bc1-a220-a7e6eb45fde0","d34c0e8b-11fa-4410-a673-2412aea39569"]
The function returns a single text string in square brackets which is a comma-separated list of GUIDs.
This comma-separated list of GUIDs can easily be parsed into separated cells using the TEXTSPLIT function.
= TEXTSPLIT ( C2, , {""",""","[","]",""""}, TRUE )
The above formula will split the list of comma-separated GUIDs based on these sets of characters ","
, [
, ]
, "
in that order.
TEXTSPLIT splits these GUIDs into rows and then also removed any blank cells to leave only the GUIDs each in its own cell.
Generate a GUID with Power Query
Power Query is loading and transforming your data. It also has a fairly easy way to create GUIDs.
The Power Query formula language includes a Text.NewGuid function which will generate a GUID for you.
This means when you are importing or transforming a data set, you can add a column of GUIDs.
You can import your data into Power Query through these steps.
- Select your table.
- Go to the Data tab.
- Click on the From Table/Range command.
Now the dataset is in the Power Query editor. Go to the Add Column tab and press the Custom Column button in the General section.
This will open the Custom Column formula editor.
#table({"GUID"},{{Text.NewGuid()}})[GUID]{0}
Give your new column a name and enter the above formula into the Custom column formula input, then press the OK button.
This part #table({"GUID"},{{Text.NewGuid()}})
creates a table with a single column named GUID and a single row containing a GUID value.
Then [GUID]{0}
will get the zeroth row in the GUID column. In other words, it gets the GUID value out of the table that was created.
⚠️ Warning: Unfortunately, you can’t just use the formula =Text.NewGuid()
, this will result in each row having the same GUID when it’s loaded to Excel. Creating a table #table()
with the formula seems to work and results in different GUIDs across the rows.
This creates a new column in the data preview with a different GUID value in each row.
This can then be loaded back into Excel. Go to the Home tab of the Power Query editor and press the Close and Load button.
Generate a GUID with Power Automate
Power Automate has the ability to connect to Excel spreadsheets saved in SharePoint or OneDrive. This means you can automate processes involving Excel and other cloud apps.
Power Automate comes with its own workflow expression language which contains a guid function.
This can be used to create GUIDs and add them to an Excel table.
You generally won’t want your GUIDs to change, so this method is great because it will add static values to Excel. Whereas the previous methods will produce GUIDs that will change when you refresh Excel.
You can easily make a simple flow that will add GUIDs to an Excel table with these steps.
- Go to https://make.powerautomate.com/ and create a new flow using the button trigger.
- Add the Add a row into a table action to the flow.
- Select the Excel file and table to which you want to add your GUIDs from the Location, Document Library, File, and Table dropdowns.
When you select the Table, a list of columns in the table will appear in the action.
- Click in the column to add the GUID.
- Click on the Expression tab in the popup.
- Enter
guid()
in the formula bar. - Click the Update button.
- Save the flow.
Now when you run the flow it will add a GUID to the table!
Generate a GUID with VBA
You might not want to save your spreadsheet in the cloud to use Power Automate, but still want a way to create static GUIDs.
This is where VBA might be useful.
You can create a macro to create and enter GUIDs in your workbook without the need for an external tool.
Go to the Developer tab and click on the Visual Basic command to open the visual basic editor. Alternatively, you can press Alt + F11 to open the editor.
Inside the visual basic editor, go to the Insert menu and select the Module option. This is where you can add the macro code.
The code relies on two functions and a procedure. You will need to copy and paste all of them into the module.
Function randBetween(ByVal min As Long, max As Long)
randBetween = Int(Rnd() * (max - min + 1)) + min
End Function
This function allows you to generate a random number between a min and a max value.
Function GUID()
Dim guid1, guid2, guid3, guid4, guid5, guid6, guid7, guid8 As String
guid1 = LCase(Hex(randBetween(0, 65535)))
guid2 = LCase(Hex(randBetween(0, 65535)))
guid3 = LCase(Hex(randBetween(0, 65535)))
guid4 = LCase(Hex(randBetween(0, 65535)))
guid5 = LCase(Hex(randBetween(0, 65535)))
guid6 = LCase(Hex(randBetween(0, 65535)))
guid7 = LCase(Hex(randBetween(0, 65535)))
guid8 = LCase(Hex(randBetween(0, 65535)))
guid1 = Right(String(4, "0") & guid1, 4)
guid2 = Right(String(4, "0") & guid2, 4)
guid3 = Right(String(4, "0") & guid3, 4)
guid4 = Right(String(4, "0") & guid4, 4)
guid5 = Right(String(4, "0") & guid5, 4)
guid6 = Right(String(4, "0") & guid6, 4)
guid7 = Right(String(4, "0") & guid7, 4)
guid8 = Right(String(4, "0") & guid8, 4)
GUID = guid1 & guid2 & "-" & guid3 & "-" & guid4 & "-" & guid5 & "-" & guid6 & guid7 & guid8
End Function
The above function allows you to create a GUID and it relies on the previous randBetween()
VBA function to generate the hex values.
Sub GenerateGUID()
Dim rng As Range
For Each rng In Selection
rng.Value = GUID()
Next rng
End Sub
The subroutine then loops through each cell in the selected range and adds a GUID generated from the GUID()
VBA function.
All you need to do to use this is select the range of cells to which you’d like to add GUID values, then run the GenerateGUID macro.
Generate a GUID with Office Scripts
Another way to add static GUIDs in a range is with Office Scripts.
Go to the Automate tab and click on the New Script command.
function main(workbook: ExcelScript.Workbook) {
//Create a range object from selected range
let selectedRange = workbook.getSelectedRange();
//Get dimensions of selected range
let rowHeight = selectedRange.getRowCount();
let colWidth = selectedRange.getColumnCount();
//Loop through each item in the selected range
for (let i = 0; i < rowHeight; i++) {
for (let j = 0; j < colWidth; j++) {
selectedRange.getCell(i, j).setValue(guid());
}
}
};
function randBetween(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
function guid() {
let guid1 = randBetween(0, 4294967295).toString(16).padStart(8, '0');
let guid2 = randBetween(0, 65535).toString(16).padStart(4, '0');
let guid3 = randBetween(0, 65535).toString(16).padStart(4, '0');
let guid4 = randBetween(0, 65535).toString(16).padStart(4, '0');
let guid5 = randBetween(0, 4294967295).toString(16).padStart(8, '0');
let guid6 = randBetween(0, 65535).toString(16).padStart(4, '0');
let guid = guid1 + '-' + guid2 + '-' + guid3 + '-' + guid4 + '-' + guid5 + guid6;
return guid;
};
This will open up the Code Editor and you can paste in the above code.
This code consists of three functions.
randBetween()
is a function that allows you to generate a random number between a minimum and a maximum.guid()
uses therandBetween()
function to generate the GUID in a similar way to the first method with the RANDBETWEEN Excel function..toString(16)
will convert the random number to its hex value..padStart(8, '0')
ensures the hex value is 8 characters.
The main()
then loops through the selected range and populates a GUID in each cell using the guid()
function.
All you need to do is select a range of cells in which you’d like to add GUID values and then run the script.
Conclusions
GUIDs are very commonly used for uniquely identifying items in a database. When working with data in Excel, there are a number of ways to generate a GUID in Excel.
If you need to generate a GUID quickly and don’t mind using an external service, the WEBSERVICE function may be the best option.
For those who prefer working entirely within the RANDBETWEEN or Power Query methods will be the way to go. However, these will create volatile GUIDs that change when the spreadsheet is refreshed.
Using Power Automate, VBA, or Office Scripts all provide a way to generate GUIDs in Excel that are static and won’t continuously change.
Have you ever needed to create GUIDs in Excel? How did you create them? Let me know in the comments below!
About the Author
John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.
I have an excel file with one order on each row, and I want each order to have a unique identifier, so there will be a Unique ID column. Every time I fill a row, I want Excel to automatically populate the Unique ID column for me. I did some research and was pointed in the direction of GUIDs. I found the following code:
Function GenGuid() As String
Dim TypeLib As Object
Dim Guid As String
Set TypeLib = CreateObject("Scriptlet.TypeLib")
Guid = TypeLib.Guid
' format is {24DD18D4-C902-497F-A64B-28B2FA741661}
Guid = Replace(Guid, "{", "")
Guid = Replace(Guid, "}", "")
Guid = Replace(Guid, "-", "")
GenGuid = Guid
End Function
but I am not sure how I can implement it. Any help would be greatly appreciated. Thank you in advance.
armstrhb
4,0243 gold badges20 silver badges28 bronze badges
asked Aug 11, 2011 at 19:00
3
The following Excel expression evaluates to a V4 GUID:
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,65535),4),"-",DEC2HEX(RANDBETWEEN(16384,20479),4),"-",DEC2HEX(RANDBETWEEN(32768,49151),4),"-",DEC2HEX(RANDBETWEEN(0,65535),4),DEC2HEX(RANDBETWEEN(0,4294967295),8))
-or (depending on locale setting/decimal and list separators)-
=CONCATENATE(DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";DEC2HEX(RANDBETWEEN(0;65535);4);"-";DEC2HEX(RANDBETWEEN(16384;20479);4);"-";DEC2HEX(RANDBETWEEN(32768;49151);4);"-";DEC2HEX(RANDBETWEEN(0;65535);4);DEC2HEX(RANDBETWEEN(0;4294967295);8))
Note that the first character of the third group is always 4 to signify a V4 (pseudo-random number generated) GUID/UUID per RFC 4122 section 4.4.
Also note that the first character of the fourth group is always between 8 and B per the same RFC.
Standard disclaimer: the resulting GUIDs/UUIDs are not cryptographically strong.
Edit: remove invisible characters
Stephen
4306 silver badges6 bronze badges
answered Aug 31, 2012 at 17:07
NekojiruSouNekojiruSou
6157 silver badges11 bronze badges
5
I used the following function in v.2013 excel vba to create a GUID and is working well..
Public Function GetGUID() As String
GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36)
End Function
answered Apr 17, 2014 at 7:02
rchackorchacko
1,94722 silver badges24 bronze badges
3
I know this question is answered, but I think the code in question should look something like what’s on this page: http://snipplr.com/view/37940/
Haven’t tested, but this code seems to tap into the Windows API to get its GUID’s — I would try putting that in a public module and typing =GetGUId()
in an Excel cell to see what I’d get. If it works in VB6 you have a great deal of a good chance it works in VBA as well:
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long
Public Function GetGUID() As String
'(c) 2000 Gus Molina
Dim udtGUID As GUID
If (CoCreateGuid(udtGUID) = 0) Then
GetGUID = _
String(8 - Len(Hex$(udtGUID.Data1)), "0") & Hex$(udtGUID.Data1) & _
String(4 - Len(Hex$(udtGUID.Data2)), "0") & Hex$(udtGUID.Data2) & _
String(4 - Len(Hex$(udtGUID.Data3)), "0") & Hex$(udtGUID.Data3) & _
IIf((udtGUID.Data4(0) < &H10), "0", "") & Hex$(udtGUID.Data4(0)) & _
IIf((udtGUID.Data4(1) < &H10), "0", "") & Hex$(udtGUID.Data4(1)) & _
IIf((udtGUID.Data4(2) < &H10), "0", "") & Hex$(udtGUID.Data4(2)) & _
IIf((udtGUID.Data4(3) < &H10), "0", "") & Hex$(udtGUID.Data4(3)) & _
IIf((udtGUID.Data4(4) < &H10), "0", "") & Hex$(udtGUID.Data4(4)) & _
IIf((udtGUID.Data4(5) < &H10), "0", "") & Hex$(udtGUID.Data4(5)) & _
IIf((udtGUID.Data4(6) < &H10), "0", "") & Hex$(udtGUID.Data4(6)) & _
IIf((udtGUID.Data4(7) < &H10), "0", "") & Hex$(udtGUID.Data4(7))
End If
End Function
Thanks Gus Molina!
If this code works (which I don’t doubt), I think you’d get a new set of GUID’s whenever the function gets evaluated, which means everytime the sheet gets calculated — when you’re saving the workbook, for example. Make sure to copy-pastespecial-values if you need the GUID’s for later use… which is somewhat likely.
answered Jan 24, 2013 at 5:55
Mathieu GuindonMathieu Guindon
69.4k8 gold badges110 silver badges232 bronze badges
2
A VBA approach based on generating random numbers using the Rnd()
function, and not on external API calls or Scriptlet.TypeLib
:
Public Function CreateGUID() As String
Do While Len(CreateGUID) < 32
If Len(CreateGUID) = 16 Then
'17th character holds version information
CreateGUID = CreateGUID & Hex$(8 + CInt(Rnd * 3))
End If
CreateGUID = CreateGUID & Hex$(CInt(Rnd * 15))
Loop
CreateGUID = "{" & Mid(CreateGUID, 1, 8) & "-" & Mid(CreateGUID, 9, 4) & "-" & Mid(CreateGUID, 13, 4) & "-" & Mid(CreateGUID, 17, 4) & "-" & Mid(CreateGUID, 21, 12) & "}"
End Function
This essentially is a VBA implementation of NekojiruSou’s answer (it also generates a v4 GUID), and carries the same limitations, but will work in VBA and might be easier to implement.
Note that you can omit the last line to not return the dashes and curly braces in the result.
answered Sep 28, 2017 at 16:31
Erik AErik A
31.4k12 gold badges44 silver badges65 bronze badges
0
I found pretty solution here:
http://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=751237&msg=8634441
Option Explicit
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "ole32" (pguid As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32" ( _
rguid As GUID, ByVal lpsz As Long, ByVal cchMax As Long) As Long
Public Function CreateGUID() As String
Dim NewGUID As GUID
CoCreateGuid NewGUID
CreateGUID = Space$(38)
StringFromGUID2 NewGUID, StrPtr(CreateGUID), 39
End Function
answered Nov 24, 2017 at 11:24
AlekzanderAlekzander
8263 gold badges12 silver badges12 bronze badges
This is based on a javascript implementation.
Private Function getGUID() As String
Call Randomize 'Ensure random GUID generated
getGUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
getGUID = Replace(getGUID, "y", Hex(Rnd() And &H3 Or &H8))
Dim i As Long: For i = 1 To 30
getGUID = Replace(getGUID, "x", Hex$(Int(Rnd() * 16)), 1, 1)
Next
End Function
answered May 21, 2021 at 10:48
SancarnSancarn
2,54318 silver badges43 bronze badges
3
Same same for german Excel version:
=VERKETTEN(DEZINHEX(ZUFALLSBEREICH(0;4294967295);8);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);"-";DEZINHEX(ZUFALLSBEREICH(16384;20479);4);"-";DEZINHEX(ZUFALLSBEREICH(32768;49151);4);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);DEZINHEX(ZUFALLSBEREICH(0;4294967295);8))
answered Dec 19, 2012 at 11:47
ChakeChake
931 silver badge9 bronze badges
1
Since windows update taken out «Scriptlet.TypeLib», try the following:
Declare Function CoCreateGuid Lib "ole32" (ByRef GUID As Byte) As Long
Public Function GenerateGUID() As String
Dim ID(0 To 15) As Byte
Dim N As Long
Dim GUID As String
Dim Res As Long
Res = CoCreateGuid(ID(0))
For N = 0 To 15
GUID = GUID & IIf(ID(N) < 16, "0", "") & Hex$(ID(N))
If Len(GUID) = 8 Or Len(GUID) = 13 Or Len(GUID) = 18 Or Len(GUID) = 23 Then
GUID = GUID & "-"
End If
Next N
GenerateGUID = GUID
End Function
Alternatively,
if you are connecting to SQL Server 2008 or higher, try to use the SQL NEWID() function instead.
answered Jan 25, 2018 at 2:54
rchackorchacko
1,94722 silver badges24 bronze badges
1
I created a VBA function that works both on mac and windows:
https://github.com/Martin-Carlsson/Business-Intelligence-Goodies/blob/master/Excel/GenerateGiud/GenerateGiud.bas
'Generates a guid, works on both mac and windows
Function Guid() As String
Guid = RandomHex(3) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(6)
End Function
'From: https://www.mrexcel.com/forum/excel-questions/301472-need-help-generate-hexadecimal-codes-randomly.html#post1479527
Private Function RandomHex(lngCharLength As Long)
Dim i As Long
Randomize
For i = 1 To lngCharLength
RandomHex = RandomHex & Right$("0" & Hex(Rnd() * 256), 2)
Next
End Function
answered Apr 10, 2019 at 9:43
Martin CarlssonMartin Carlsson
4512 gold badges6 silver badges17 bronze badges
I recently ran into problems using CreateObject(«Scriptlet.TypeLib») in some vba code.
So based on NekojiruSou excel functions wrote the following which should work without any specific excel functions. This can be used to develop a user defined function in excel.
Public Function Get_NewGUID() As String
'Returns GUID as string 36 characters long
Randomize
Dim r1a As Long
Dim r1b As Long
Dim r2 As Long
Dim r3 As Long
Dim r4 As Long
Dim r5a As Long
Dim r5b As Long
Dim r5c As Long
'randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
r1a = RandomBetween(0, 65535)
r1b = RandomBetween(0, 65535)
r2 = RandomBetween(0, 65535)
r3 = RandomBetween(16384, 20479)
r4 = RandomBetween(32768, 49151)
r5a = RandomBetween(0, 65535)
r5b = RandomBetween(0, 65535)
r5c = RandomBetween(0, 65535)
Get_NewGUID = (PadHex(r1a, 4) & PadHex(r1b, 4) & "-" & PadHex(r2, 4) & "-" & PadHex(r3, 4) & "-" & PadHex(r4, 4) & "-" & PadHex(r5a, 4) & PadHex(r5b, 4) & PadHex(r5c, 4))
End Function
Public Function Floor(ByVal X As Double, Optional ByVal Factor As Double = 1) As Double
'From: http://www.tek-tips.com/faqs.cfm?fid=5031
' X is the value you want to round
' Factor is the multiple to which you want to round
Floor = Int(X / Factor) * Factor
End Function
Public Function RandomBetween(ByVal StartRange As Long, ByVal EndRange As Long) As Long
'Based on https://msdn.microsoft.com/en-us/library/f7s023d2(v=vs.90).aspx
' randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
RandomBetween = CLng(Floor((EndRange - StartRange + 1) * Rnd())) + StartRange
End Function
Public Function PadLeft(text As Variant, totalLength As Integer, padCharacter As String) As String
'Based on https://stackoverflow.com/questions/12060347/any-method-equivalent-to-padleft-padright
' with a little more checking of inputs
Dim s As String
Dim inputLength As Integer
s = CStr(text)
inputLength = Len(s)
If padCharacter = "" Then
padCharacter = " "
ElseIf Len(padCharacter) > 1 Then
padCharacter = Left(padCharacter, 1)
End If
If inputLength < totalLength Then
PadLeft = String(totalLength - inputLength, padCharacter) & s
Else
PadLeft = s
End If
End Function
Public Function PadHex(number As Long, length As Integer) As String
PadHex = PadLeft(Hex(number), 4, "0")
End Function
answered Jul 21, 2017 at 19:48
1
For generating random guids using just the Rnd()
function, not using any libraries or APIs, the simplest I can think of is this:
' UUID Version 4 (random)
Function GetUUID4()
Dim guid As String
Dim i As Integer
Dim r As Integer
guid = ""
Randomize
For i = 0 To 31
' random digit 0..15
r = Rnd() * 15
' add dash separators
If (i = 8) Or (i = 12) Or (i = 16) Or (i = 20) Then guid = guid & "-"
' uuid4 version info in 12th and 16th digits
If (i = 12) Then r = 4
If (i = 16) Then r = (r And 3 Or 8)
' add as hex digit
guid = guid & Hex(r)
Next i
GetUUID4 = guid
End Function
answered Apr 6, 2021 at 14:12
BdRBdR
2,5992 gold badges16 silver badges36 bronze badges
If you are inserting records into a database you can use this way to make a GUID.
It is probably the most simplest and easiest way to implement as you don’t need a complex VBA
function as you use the built in SQL function.
The statement uses NewID()
,
The syntax is as follows,
INSERT INTO table_name (ID,Column1,Column2,Column3)
VALUES (NewID(),value1,value2,value3)
In VBA
syntax it is as follows,
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (NewID(),value1,value2,value3)"
And if you need to concatenate values, just treat it as a string and concatenate as you would normally for a SQL statement,
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (" & "NewID()" & "," & "value1" & "," & "value2" & "," & "value3" & ")"
answered Jan 21, 2017 at 6:00
KyloRenKyloRen
2,6915 gold badges28 silver badges57 bronze badges
2
Function funGetGuid() As String
Const URL As String = "http://www.guidgen.com/"
Const strMask As String = "value="
Dim l As Long
Dim txt As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.send
txt = .responseText
End With
Do
l = InStr(l + 1, txt, strMask)
If l = 0 Then Exit Do
funGetGuid = Mid$(txt, l + Len(strMask) + 1, 36)
Loop
End Function
Echilon
10k32 gold badges133 silver badges216 bronze badges
answered Nov 5, 2015 at 21:44
1
-
May 3 2020, 19:31
Потребовалась короткая и эффективная функция для генерации Guid на VBA Excel. После недолгого поиска нашел эту старую, но не потерявшую актуальность переписку на форуме с описанием кода генератора: Получить GUID из VBA Excel. Но поскольку у меня 64-битная версия компа, то с ходу функция не заработала. Пришлось делать следующие две правки:
1) VBA Private Declare Function не опознается
2) StrPtr type mismatch in 64 bit mode
В итоге в таком варианте заработало. Согласен с Taranaga, который на форуме написал:
«Я в шоке — ничего не понятно, но, зараза, РАБОТАЕТ! ))»
Option Explicit Private Type GUID Data1 As Long Data2 As Integer Data3 As Integer Data4(0 To 7) As Byte End Type Private Declare PtrSafe Function CoCreateGuid Lib "ole32" (pguid As GUID) As LongPtr Private Declare PtrSafe Function StringFromGUID2 Lib "ole32" ( _ rguid As GUID, ByVal lpsz As LongPtr, ByVal cchMax As LongPtr) As LongPtr Public Function CreateGUID() As String Dim NewGUID As GUID CoCreateGuid NewGUID CreateGUID = Space$(38) StringFromGUID2 NewGUID, StrPtr(CreateGUID), 39 End Function
В качестве современной версии Excel, там’ы синтаксис с запятыми, а не точками с запятой. Я’м размещение этого ответа для удобства людей, чтобы они не’т придется заменить струны — мы’вновь все лень… средства в размере… человека, верно?
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4))
Или, если вы любите меня, не любите, когда идентификатор GUID кричит и кричит и вы, мы можем пойти в нижнем регистре, как это.
=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,42949),4),»-«,DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4)))
У меня есть файл Excel с одним заказом в каждой строке, и я хочу, чтобы каждый заказ имел уникальный идентификатор, поэтому будет столбец Уникальный идентификатор. Каждый раз, когда я заполняю строку, я хочу, чтобы Excel автоматически заполнял за меня столбец «Уникальный идентификатор». Я провел небольшое исследование и обратил внимание на GUID. Я нашел следующий код:
Function GenGuid() As String
Dim TypeLib As Object
Dim Guid As String
Set TypeLib = CreateObject("Scriptlet.TypeLib")
Guid = TypeLib.Guid
' format is {24DD18D4-C902-497F-A64B-28B2FA741661}
Guid = Replace(Guid, "{", "")
Guid = Replace(Guid, "}", "")
Guid = Replace(Guid, "-", "")
GenGuid = Guid
End Function
Но я не уверен, как я могу это реализовать. Любая помощь будет принята с благодарностью. Заранее спасибо.
13 ответов
Лучший ответ
Следующее выражение Excel оценивается как GUID V4:
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,65535),4),"-",DEC2HEX(RANDBETWEEN(16384,20479),4),"-",DEC2HEX(RANDBETWEEN(32768,49151),4),"-",DEC2HEX(RANDBETWEEN(0,65535),4),DEC2HEX(RANDBETWEEN(0,4294967295),8))
-или (в зависимости от настроек локали / десятичных разделителей и разделителей списка) —
=CONCATENATE(DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";DEC2HEX(RANDBETWEEN(0;65535);4);"-";DEC2HEX(RANDBETWEEN(16384;20479);4);"-";DEC2HEX(RANDBETWEEN(32768;49151);4);"-";DEC2HEX(RANDBETWEEN(0;65535);4);DEC2HEX(RANDBETWEEN(0;4294967295);8))
Обратите внимание, что первый символ третьей группы всегда равен 4 для обозначения GUID / UUID V4 (генерируемого псевдослучайного числа) согласно RFC 4122, раздел 4.4.
Также обратите внимание, что первый символ четвертой группы всегда находится между 8 и B в одном и том же RFC.
Стандартный отказ от ответственности: полученные идентификаторы GUID / UUID не являются криптостойкими.
Изменить: удалить невидимые символы
49
Stephen
6 Апр 2021 в 14:24
То же самое для немецкой версии Excel:
=VERKETTEN(DEZINHEX(ZUFALLSBEREICH(0;4294967295);8);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);"-";DEZINHEX(ZUFALLSBEREICH(16384;20479);4);"-";DEZINHEX(ZUFALLSBEREICH(32768;49151);4);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);DEZINHEX(ZUFALLSBEREICH(0;4294967295);8))
2
Chake
19 Дек 2012 в 15:47
Поскольку обновление Windows извлекает «Scriptlet.TypeLib», попробуйте следующее:
Declare Function CoCreateGuid Lib "ole32" (ByRef GUID As Byte) As Long
Public Function GenerateGUID() As String
Dim ID(0 To 15) As Byte
Dim N As Long
Dim GUID As String
Dim Res As Long
Res = CoCreateGuid(ID(0))
For N = 0 To 15
GUID = GUID & IIf(ID(N) < 16, "0", "") & Hex$(ID(N))
If Len(GUID) = 8 Or Len(GUID) = 13 Or Len(GUID) = 18 Or Len(GUID) = 23 Then
GUID = GUID & "-"
End If
Next N
GenerateGUID = GUID
End Function
В качестве альтернативы,
Если вы подключаетесь к SQL Server 2008 или более поздней версии, попробуйте вместо этого использовать функцию SQL NEWID ().
2
rchacko
25 Янв 2018 в 05:54
Я использовал следующую функцию в v.2013 excel vba для создания GUID и работает хорошо ..
Public Function GetGUID() As String
GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36)
End Function
34
rchacko
25 Сен 2014 в 06:04
Я создал функцию VBA, которая работает как на Mac, так и в Windows:
https://github.com/Martin-Carlsson/Business-Intelligence-Goodies/blob/master/Excel/GenerateGiud/GenerateGiud.bas
'Generates a guid, works on both mac and windows
Function Guid() As String
Guid = RandomHex(3) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(6)
End Function
'From: https://www.mrexcel.com/forum/excel-questions/301472-need-help-generate-hexadecimal-codes-randomly.html#post1479527
Private Function RandomHex(lngCharLength As Long)
Dim i As Long
Randomize
For i = 1 To lngCharLength
RandomHex = RandomHex & Right$("0" & Hex(Rnd() * 256), 2)
Next
End Function
2
Martin Carlsson
10 Апр 2019 в 12:43
Это основано на реализации javascript.
Private Function getGUID() As String
getGUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
getGUID = Replace(getGUID, "y", Hex(Rnd() And &H3 Or &H8))
Dim i As Long: For i = 1 To 30
getGUID = Replace(getGUID, "x", Hex$(Application.RoundDown(Rnd() * 15.9999,0)), 1, 1)
Next
End Function
3
Sancarn
19 Июн 2022 в 21:25
Я знаю, что на этот вопрос дан ответ, но я думаю, что рассматриваемый код должен выглядеть примерно так, как на этой странице: http://snipplr.com/ view / 37940 /
Не тестировал, но этот код, похоже, подключается к Windows API, чтобы получить его GUID — я бы попробовал поместить его в общедоступный модуль и набрать =GetGUId()
в ячейке Excel, чтобы посмотреть, что я получу. Если он работает в VB6, велика вероятность, что он работает и в VBA:
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long
Public Function GetGUID() As String
'(c) 2000 Gus Molina
Dim udtGUID As GUID
If (CoCreateGuid(udtGUID) = 0) Then
GetGUID = _
String(8 - Len(Hex$(udtGUID.Data1)), "0") & Hex$(udtGUID.Data1) & _
String(4 - Len(Hex$(udtGUID.Data2)), "0") & Hex$(udtGUID.Data2) & _
String(4 - Len(Hex$(udtGUID.Data3)), "0") & Hex$(udtGUID.Data3) & _
IIf((udtGUID.Data4(0) < &H10), "0", "") & Hex$(udtGUID.Data4(0)) & _
IIf((udtGUID.Data4(1) < &H10), "0", "") & Hex$(udtGUID.Data4(1)) & _
IIf((udtGUID.Data4(2) < &H10), "0", "") & Hex$(udtGUID.Data4(2)) & _
IIf((udtGUID.Data4(3) < &H10), "0", "") & Hex$(udtGUID.Data4(3)) & _
IIf((udtGUID.Data4(4) < &H10), "0", "") & Hex$(udtGUID.Data4(4)) & _
IIf((udtGUID.Data4(5) < &H10), "0", "") & Hex$(udtGUID.Data4(5)) & _
IIf((udtGUID.Data4(6) < &H10), "0", "") & Hex$(udtGUID.Data4(6)) & _
IIf((udtGUID.Data4(7) < &H10), "0", "") & Hex$(udtGUID.Data4(7))
End If
End Function
Спасибо, Гас Молина!
Если этот код работает (в чем я не сомневаюсь), я думаю, вы получите новый набор GUID всякий раз, когда функция будет оценена, что означает каждый раз, когда вычисляется лист — например, когда вы сохраняете книгу. Обязательно скопируйте-pastespecial-values, если вам понадобятся идентификаторы GUID для дальнейшего использования … что весьма вероятно.
11
Mathieu Guindon
24 Янв 2013 в 09:55
Подход VBA, основанный на генерации случайных чисел с помощью функции Rnd()
, а не на внешних вызовах API или Scriptlet.TypeLib
:
Public Function CreateGUID() As String
Do While Len(CreateGUID) < 32
If Len(CreateGUID) = 16 Then
'17th character holds version information
CreateGUID = CreateGUID & Hex$(8 + CInt(Rnd * 3))
End If
CreateGUID = CreateGUID & Hex$(CInt(Rnd * 15))
Loop
CreateGUID = "{" & Mid(CreateGUID, 1, 8) & "-" & Mid(CreateGUID, 9, 4) & "-" & Mid(CreateGUID, 13, 4) & "-" & Mid(CreateGUID, 17, 4) & "-" & Mid(CreateGUID, 21, 12) & "}"
End Function
По сути, это реализация ответа NekojiruSou на VBA (он также генерирует GUID v4) и имеет те же ограничения, но будет работать в VBA и может быть проще в реализации.
Обратите внимание, что вы можете опустить последнюю строку, чтобы в результате не возвращались тире и фигурные скобки.
5
Erik A
28 Сен 2017 в 19:31
Я нашел здесь хорошее решение:
http: // www .sql.ru / forum / actualutils.aspx? action = gotomsg & tid = 751237 & msg = 8634441
Option Explicit
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "ole32" (pguid As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32" ( _
rguid As GUID, ByVal lpsz As Long, ByVal cchMax As Long) As Long
Public Function CreateGUID() As String
Dim NewGUID As GUID
CoCreateGuid NewGUID
CreateGUID = Space$(38)
StringFromGUID2 NewGUID, StrPtr(CreateGUID), 39
End Function
5
Alekzander
24 Ноя 2017 в 14:24
Для генерации случайных руководств с использованием только функции Rnd()
, без использования каких-либо библиотек или API, самое простое, что я могу придумать, это следующее:
' UUID Version 4 (random)
Function GetUUID4()
Dim guid As String
Dim i As Integer
Dim r As Integer
guid = ""
Randomize
For i = 0 To 31
' random digit 0..15
r = Rnd() * 15
' add dash separators
If (i = 8) Or (i = 12) Or (i = 16) Or (i = 20) Then guid = guid & "-"
' uuid4 version info in 12th and 16th digits
If (i = 12) Then r = 4
If (i = 16) Then r = (r And 3 Or 8)
' add as hex digit
guid = guid & Hex(r)
Next i
GetUUID4 = guid
End Function
Function funGetGuid() As String
Const URL As String = "http://www.guidgen.com/"
Const strMask As String = "value="
Dim l As Long
Dim txt As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.send
txt = .responseText
End With
Do
l = InStr(l + 1, txt, strMask)
If l = 0 Then Exit Do
funGetGuid = Mid$(txt, l + Len(strMask) + 1, 36)
Loop
End Function
-5
Echilon
29 Ноя 2016 в 12:53
Если вы вставляете записи в базу данных, вы можете использовать этот способ для создания GUID.
Это, вероятно, самый простой и легкий способ реализовать, поскольку вам не нужна сложная функция VBA
, поскольку вы используете встроенную функцию SQL.
В заявлении используется NewID()
,
Синтаксис следующий:
INSERT INTO table_name (ID,Column1,Column2,Column3)
VALUES (NewID(),value1,value2,value3)
В синтаксисе VBA
это выглядит следующим образом:
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (NewID(),value1,value2,value3)"
И если вам нужно объединить значения, просто обработайте его как строку и объедините, как обычно для оператора SQL,
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (" & "NewID()" & "," & "value1" & "," & "value2" & "," & "value3" & ")"
0
KyloRen
17 Июл 2017 в 05:13
Недавно я столкнулся с проблемами при использовании CreateObject («Scriptlet.TypeLib») в некотором коде vba.
Итак, на основе функций Excel NekojiruSou написал следующее, которое должно работать без каких-либо конкретных функций Excel. Это можно использовать для разработки пользовательской функции в Excel.
Public Function Get_NewGUID() As String
'Returns GUID as string 36 characters long
Randomize
Dim r1a As Long
Dim r1b As Long
Dim r2 As Long
Dim r3 As Long
Dim r4 As Long
Dim r5a As Long
Dim r5b As Long
Dim r5c As Long
'randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
r1a = RandomBetween(0, 65535)
r1b = RandomBetween(0, 65535)
r2 = RandomBetween(0, 65535)
r3 = RandomBetween(16384, 20479)
r4 = RandomBetween(32768, 49151)
r5a = RandomBetween(0, 65535)
r5b = RandomBetween(0, 65535)
r5c = RandomBetween(0, 65535)
Get_NewGUID = (PadHex(r1a, 4) & PadHex(r1b, 4) & "-" & PadHex(r2, 4) & "-" & PadHex(r3, 4) & "-" & PadHex(r4, 4) & "-" & PadHex(r5a, 4) & PadHex(r5b, 4) & PadHex(r5c, 4))
End Function
Public Function Floor(ByVal X As Double, Optional ByVal Factor As Double = 1) As Double
'From: http://www.tek-tips.com/faqs.cfm?fid=5031
' X is the value you want to round
' Factor is the multiple to which you want to round
Floor = Int(X / Factor) * Factor
End Function
Public Function RandomBetween(ByVal StartRange As Long, ByVal EndRange As Long) As Long
'Based on https://msdn.microsoft.com/en-us/library/f7s023d2(v=vs.90).aspx
' randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
RandomBetween = CLng(Floor((EndRange - StartRange + 1) * Rnd())) + StartRange
End Function
Public Function PadLeft(text As Variant, totalLength As Integer, padCharacter As String) As String
'Based on https://stackoverflow.com/questions/12060347/any-method-equivalent-to-padleft-padright
' with a little more checking of inputs
Dim s As String
Dim inputLength As Integer
s = CStr(text)
inputLength = Len(s)
If padCharacter = "" Then
padCharacter = " "
ElseIf Len(padCharacter) > 1 Then
padCharacter = Left(padCharacter, 1)
End If
If inputLength < totalLength Then
PadLeft = String(totalLength - inputLength, padCharacter) & s
Else
PadLeft = s
End If
End Function
Public Function PadHex(number As Long, length As Integer) As String
PadHex = PadLeft(Hex(number), 4, "0")
End Function
1
mphase
21 Июл 2017 в 22:48
1. Excel генерирует guid, формат uuid: 600d65bc-948a-1260-2217-fd8dfeebb1cd
=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),"-",DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4),"-","4",DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",DEC2HEX(RANDBETWEEN(8,11)),DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4)))
2. Excel генерирует guid, формат uuid: 600d65bc948a12602217fd8dfeebb1cd
=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),"",DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4),"","4",DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"",DEC2HEX(RANDBETWEEN(8,11)),DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"",DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4)))
3. Формат guid и uuid, сгенерированный в Excel: 4E3B14BB-ECF3-7B2E-A5A2-FE6E1A52DE6A
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),"-",DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4),"-","4",DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",DEC2HEX(RANDBETWEEN(8,11)),DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"-",DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4))
4. Excel генерирует guid, формат uuid: 4E3B14BBECF37B2E-A5A2FE6E1A52DE6A
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),"",DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4),"","4",DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"",DEC2HEX(RANDBETWEEN(8,11)),DEC2HEX(RANDBETWEEN(0,POWER(16,3)),3),"",DEC2HEX(RANDBETWEEN(0,POWER(16,8)),8),DEC2HEX(RANDBETWEEN(0,POWER(16,4)),4))
Приветствую
Надо как-то в Excel или в LibreOffice настроить автоматическую генерацию уникального числа у каждой строки с заполненными данными.
Есть два столбца — ID (столбец №1) и имя человека (столбец №2). Если добавляю новое имя в столбец №2, то в этой строке в столбце №1 должен появиться уникальный идентификатор, к примеру, цифровой код (цифра). Но есть одна особенность. Допустим, что есть пять записей в файле с айдишниками с 1 по 5. Я удаляю пятую запись, строку целиком или очищаю ее, а затем добавляю новую запись. А вот у же у новой записи по факту шестой, но с учетом ранее удаленной записи, новая запись будет пятой, но ее ID уже не должен быть пятым, но должен быть шестым.
На картинке пояснил тремя блоками:
- добавил записи, добавились автоматом ID
- удалил пятую запись
- добавил новую запись; по факту ее ID должен быть новым, ранее не использовавшимся.
Подскажите пожалуйста реализацию.
-
Вопрос заданболее трёх лет назад
-
5452 просмотра
Пригласить эксперта
Используйте ms access или любую БД. Они для этого и предназначены.
в Excel можно реализовать через макросы, но это такой костыль, что всем костылям костыль:
Добавьте код макроса в код страницы (редактор кода vba->двойной щелчок по нужному листу в менеджере проекта), диапазон ваших значений B1:B1000
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("B1:B1000")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
X = 5
Y = 1
If Cells(Y, X).Value = "" Then Cells(Y, X).Value = 0
On Error GoTo here
If Target.Value <> "" Then
answer = MsgBox("Increment?", vbYesNo + vbQuestion, "Empty Sheet")
If answer = vbYes Then Target.Offset(0, -1).Value = Cells(Y, X).Value + 1
If answer = vbYes Then Cells(Y, X).Value = Cells(Y, X).Value + 1
Else
Target.Offset(0, -1).Value = ""
End If
here:
Debug.Print Err
End If
End Sub
Можно использовать ID на основе текущего времени, например 170911181042, 170911181057 и т.п. Со вставкой такого числа справится простенький макрос типа:
Sub typeID()
mydate = Date
mytime = Time
mydateF = Format(mydate, "yymmdd")
mytimeF = Format(mytime, "HhMmSs")
ID = mydateF & mytimeF
ActiveCell.Value = ID
End Sub
Варианты с GUID:
1. Макрос:
Public Function GetGUID() As String
GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36)
End Function
2. Формула:
=CONCATENATE(DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";DEC2HEX(RANDBETWEEN(0;42949);4);"-";DEC2HEX(RANDBETWEEN(0;42949);4);"-";DEC2HEX(RANDBETWEEN(0;42949);4);"-";DEC2HEX(RANDBETWEEN(0;4294967295);8);DEC2HEX(RANDBETWEEN(0;42949);4))
-
Показать ещё
Загружается…
15 апр. 2023, в 10:29
1500 руб./за проект
15 апр. 2023, в 10:21
2500 руб./за проект
15 апр. 2023, в 09:30
500 руб./за проект