How to run macro to only one computer

2019-09-16 04:19发布

I have a vba form . I wanted to know if there's a way for it to run only in a single computer so that if someone want's to copy it they cannot run it on another machine. I'm thinking maybe we can use a computer's mac address as a mode of security.

Anyone?


EDIT: implemented example from miroxlav's answer:

Const AllowedName As String = "CEB-L1-7440236"

Sub UserForm_click()
    If Environ$("COMPUTERNAME") <> AllowedName Then
        MsgBox ("Not authorized.")
        Exit Sub
    End If

    If vbYes <> MsgBox("Launch the macro?", vbYesNo) Then Exit Sub

    '--start of code what macro actually does
    '....
    '....
    '....
    '--end of code what macro actually does

    MsgBox ("Finsihed.")

End Sub

标签: excel vba
1条回答
We Are One
2楼-- · 2019-09-16 04:42
  1. Embed computer name into your VBA code and add a test for it.
  2. Password-protect the code module so someone else cannot see/modify it.

Maybe you would want to lock the macro rather to user name than to computer name (so the authorized user can use it on any computer), but it's on you.

' computer name
? Environ$("COMPUTERNAME")

' alternative: user name
? Application.UserName 

Example - inset Const line at the top of your macro module and If...EndIf just after your Sub macro line:

Const AllowedName As String = "abcd"
Sub UserForm_click()
    If Environ$("COMPUTERNAME") <> AllowedName Then
        MsgBox ("Not authorized.")
        Exit Sub
    End If

    '--keep your original code here--
End Sub

But this one can be relatively easily circumvented using command line:

SET COMPUTERNAME=abcd

once someone knows that abcd is proper computer name needed to run the macro. Perhaps prefer user name checking. Relevant code line will change to:

If Application.UserName <> AllowedName Then

Of course, you can also get computer's MAC address using VBA, just search "mac address vba", there are many examples.

查看更多
登录 后发表回答