Question

Altering the registry with a VB command

Asked by: themroc

On my computer is running a small programme lets say "Update.exe" which alters from time to time the values in an EXCEL file: "D:\limjax\ticker_priv.xls"
The filename and the filepath is set within the small executable "Update.exe" programme.
Now my problem. I would like to alter from time to time the name and path of the Excel file without opening the small programme "Update.exe". I figured out that I can find the entry of the filename and the filepath in the Registry. Manually I than could change the entry using the REGEDIT command. Now my question, What do I have to programme to alter the registry entry with a small VB programme??
I never worked with REISTRY entries before, so Im a little bit cautious, Is there a way not to damage to much in case somthing is going wrong.

The location of the entry in the registry is:
HKEY_CURRENT_USER\Software\programme\settings\ExportFilename "D:\limjax\ticker_priv.xls"

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2001-12-03 at 01:06:59ID20242851
Tags

vb

Topic

Visual Basic Programming

Participating Experts
5
Points
70
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Hooking the start of regedit
    I would like to know how to have my delphi app sitting in the task tray to alter a value in the registry. whenever the user runs regedit. I need my app to detect when it is regedit is loading and act before it is visible. The reason is that I dont want the user to get some in...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: thuanncPosted on 2001-12-03 at 02:26:52ID: 6663881

'Create new mudule registry.bas with following code

Option Explicit
Public Const HKEY_CLASSES_ROOT = &H80000000
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const HKEY_USERS = &H80000003
Public Const HKEY_PERFORMANCE_DATA = &H80000004
Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Declare Function RegDeleteKey Lib "advapi32.dll" Alias "RegDeleteKeyA" (ByVal hKey As Long, ByVal lpSubKey As String) As Long
Declare Function RegDeleteValue Lib "advapi32.dll" Alias "RegDeleteValueA" (ByVal hKey As Long, ByVal lpValueName As String) As Long
Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long
Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal cbData As Long) As Long
Const KEY_ALL_ACCESS = &HF003F
Const HKEY_DYN_DATA = &H80000006
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_DWORD_BIG_ENDIAN = 5
Const REG_DWORD_LITTLE_ENDIAN = 4
Const REG_EXPAND_SZ = 2
Const REG_LINK = 6
Const REG_MULTI_SZ = 7
Const REG_NONE = 0
Const REG_RESOURCE_LIST = 8
Const REG_SZ = 1

Function RegQueryStringValue(ByVal hKey As Long, ByVal strValueName As String)
    Dim lresult As Long
    Dim lValueType As Long
    Dim strBuf As String
    Dim lDataBufSize As Long
    'On Error GoTo 0
    lresult = RegQueryValueEx(hKey, strValueName, 0&, lValueType, ByVal 0&, lDataBufSize)
    If lresult = 0 Then
        If lValueType = REG_SZ Then
            strBuf = String(lDataBufSize, " ")
            lresult = RegQueryValueEx(hKey, strValueName, 0&, 0&, ByVal strBuf, lDataBufSize)
            If lresult = 0 Then
                RegQueryStringValue = Left(strBuf, lDataBufSize - 1)
            End If
        End If
    End If
End Function
Public Function GetString(hKey As Long, strPath As String, strValue As String)
    Dim keyhand&
    Call RegOpenKey(hKey, strPath, keyhand&)
    GetString = RegQueryStringValue(keyhand&, strValue)
    Call RegCloseKey(keyhand&)
End Function
Public Sub SaveString(hKey As Long, strPath As String, strValue As String, strdata As String)
    Dim keyhand&
    Call RegCreateKey(hKey, strPath, keyhand&)
    Call RegSetValueEx(keyhand&, strValue, 0, REG_SZ, ByVal strdata, Len(strdata))
    Call RegCloseKey(keyhand&)
End Sub
Public Sub DelString(hKey As Long, strPath As String, sKey As String)
    Dim keyhand&
    Call RegOpenKey(hKey, strPath, keyhand&)
    Call RegDeleteValue(keyhand&, sKey)
    Call RegCloseKey(keyhand&)
End Sub

'**********************
'in your procedure you can put following line to save 'registry value
' pth="D:\limjax\ticker_priv.xls"
'**********************
public sub SavePathtoReg(pth as string)
call SaveString(HKEY_CURRENT_USER , "Software\programme\settings", "ExportFilename", pth )
end sub

 

by: cquinnPosted on 2001-12-03 at 02:27:56ID: 6663884

Create a module and add this code:

Query the value with NewPath=Getpath()

Set it with SetPath("New Value")

===================================================

Option Explicit
Public Const sSoftwareKey = "Software\programme\settings"

Private Declare Function RegSetValueEx Lib "advapi32" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, ByVal lpData As String, ByVal cbData As Long) As Long
Private Declare Function RegCreateKeyEx Lib "advapi32" Alias "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal Reserved As Long, ByVal lpClass As String, ByVal dwOptions As Long, ByVal samDesired As Long, ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES, ByRef phkResult As Long, ByRef lpdwDisposition As Long) As Long
Private Declare Function RegOpenKeyEx Lib "advapi32" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, ByRef phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, ByRef lpType As Long, ByVal lpData As String, ByRef lpcbData As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32" (ByVal hKey As Long) As Long
' Reg Create Type Values...
Private Const REG_OPTION_RESERVED = 0           ' Parameter is reserved
Private Const REG_OPTION_NON_VOLATILE = 0       ' Key is preserved when system is rebooted
Private Const REG_OPTION_VOLATILE = 1           ' Key is not preserved when system is rebooted
Private Const REG_OPTION_CREATE_LINK = 2        ' Created key is a symbolic link
Private Const REG_OPTION_BACKUP_RESTORE = 4     ' open for backup or restore

' Reg Key Security Options...
Private Const READ_CONTROL = &H20000
Private Const KEY_QUERY_VALUE = &H1
Private Const KEY_SET_VALUE = &H2
Private Const KEY_CREATE_SUB_KEY = &H4
Private Const KEY_ENUMERATE_SUB_KEYS = &H8
Private Const KEY_NOTIFY = &H10
Private Const KEY_CREATE_LINK = &H20
Private Const KEY_ALL_ACCESS = KEY_QUERY_VALUE + KEY_SET_VALUE + _
                       KEY_CREATE_SUB_KEY + KEY_ENUMERATE_SUB_KEYS + _
                       KEY_NOTIFY + KEY_CREATE_LINK + READ_CONTROL
                     
' Reg Key ROOT Types...
Public Const HKEY_CLASSES_ROOT = &H80000000
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const HKEY_USERS = &H80000003
Public Const HKEY_PERFORMANCE_DATA = &H80000004

Private Const ERROR_SUCCESS = 0                  ' Return Value...
Private Const REG_SZ = 1                         ' Unicode nul terminated string
Private Const REG_DWORD = 4                      ' 32-bit number
Private Type SECURITY_ATTRIBUTES
    nLength As Long
    lpSecurityDescriptor As Long
    bInheritHandle As Boolean
End Type

Public iReturn As Integer
Public sExportPath As String

'------------------------------------------------------------
Public Function GetKeyValue(KeyRoot As Long, KeyName As String, SubKeyRef As String, ByRef KeyVal As Variant, Optional ByVal vDefault As Variant) As Boolean
'------------------------------------------------------------
    Dim i As Long                                           ' Loop Counter
    Dim rc As Long                                          ' Return Code
    Dim hKey As Long                                        ' Handle To An Open Registry Key
    Dim hDepth As Long                                      '
    Dim KeyValType As Long                                  ' Data Type Of A Registry Key
    Dim tmpVal As String                                    ' Tempory Storage For A Registry Key Value
    Dim KeyValSize As Long                                  ' Size Of Registry Key Variable
    '------------------------------------------------------------
    ' Open RegKey Under KeyRoot {HKEY_LOCAL_MACHINE...}
    '------------------------------------------------------------
    rc = RegOpenKeyEx(KeyRoot, KeyName, 0, KEY_ALL_ACCESS, hKey) ' Open Registry Key
   
    If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError          ' Handle Error...
   
    tmpVal = String$(1024, 0)                               ' Allocate Variable Space
    KeyValSize = 1024                                       ' Mark Variable Size
   
    '------------------------------------------------------------
    ' Retrieve Registry Key Value...
    '------------------------------------------------------------
    rc = RegQueryValueEx(hKey, SubKeyRef, 0, _
                         KeyValType, tmpVal, KeyValSize)    ' Get/Create Key Value
                       
    If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError          ' Handle Errors
   
    If (Asc(Mid(tmpVal, KeyValSize, 1)) = 0) Then           ' Win95 Adds Null Terminated String...
        tmpVal = Left(tmpVal, KeyValSize - 1)               ' Null Found, Extract From String
    Else                                                    ' WinNT Does NOT Null Terminate String...
        tmpVal = Left(tmpVal, KeyValSize)                   ' Null Not Found, Extract String Only
    End If
    '------------------------------------------------------------
    ' Determine Key Value Type For Conversion...
    '------------------------------------------------------------
    Select Case KeyValType                                  ' Search Data Types...
    Case REG_SZ                                             ' String Registry Key Data Type
        KeyVal = tmpVal                                     ' Copy String Value
    Case REG_DWORD                                          ' Double Word Registry Key Data Type
        'For i = Len(tmpVal) To 1 Step -1                    ' Convert Each Bit
        '    KeyVal = KeyVal + Hex(Asc(Mid(tmpVal, i, 1)))   ' Build Value Char. By Char.
        'Next
        'KeyVal = Format$("&h" + KeyVal)                     ' Convert Double Word To String
        KeyVal = tmpVal
    End Select
   
    GetKeyValue = True                                      ' Return Success
    rc = RegCloseKey(hKey)                                  ' Close Registry Key
    Exit Function                                           ' Exit
'------------------------------------------------------------
GetKeyError:    ' Cleanup After An Error Has Occured...
'------------------------------------------------------------
    Select Case VarType(KeyVal)
    Case vbInteger, vbSingle, vbDouble, vbLong, vbCurrency
    If IsMissing(vDefault) Then
        KeyVal = 0  ' Set Return Val To Empty String
    Else
        KeyVal = vDefault
    End If
    Case vbDate
    KeyVal = vbNull
    Case vbString
    If IsMissing(vDefault) Then
        KeyVal = ""  ' Set Return Val To Empty String
    Else
        KeyVal = vDefault
    End If
    Case vbBoolean
    If IsMissing(vDefault) Then
        KeyVal = 0  ' Set Return Val To Empty String
    Else
        KeyVal = vDefault
    End If
    Case Else
    KeyVal = vbNull
    End Select
    GetKeyValue = False                                     ' Return Failure
    rc = RegCloseKey(hKey)                                  ' Close Registry Key
'------------------------------------------------------------
End Function
'------------------------------------------------------------

'------------------------------------------------------------
Public Function UpdateKey(KeyRoot As Long, KeyName As String, SubKeyName As String, SubKeyValue As String) As Boolean
'------------------------------------------------------------
    Dim rc As Long                                      ' Return Code
    Dim hKey As Long                                    ' Handle To A Registry Key
    Dim hDepth As Long                                  '
    Dim lpAttr As SECURITY_ATTRIBUTES                   ' Registry Security Type
'------------------------------------------------------------
    lpAttr.nLength = 50                                 ' Set Security Attributes To Defaults...
    lpAttr.lpSecurityDescriptor = 0                     ' ...
    lpAttr.bInheritHandle = True                        ' ...

    '------------------------------------------------------------
    '- Create/Open Registry Key...
    '------------------------------------------------------------
    rc = RegCreateKeyEx(KeyRoot, KeyName, _
                        0, REG_SZ, _
                        REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, lpAttr, _
                        hKey, hDepth)                   ' Create/Open //KeyRoot//KeyName
   
    If (rc <> ERROR_SUCCESS) Then GoTo CreateKeyError   ' Handle Errors...
   
    '------------------------------------------------------------
    '- Create/Modify Key Value...
    '------------------------------------------------------------
    If (SubKeyValue = "") Then SubKeyValue = " "        ' A Space Is Needed For RegSetValueEx() To Work...
   
    rc = RegSetValueEx(hKey, SubKeyName, _
                       0, REG_SZ, _
                       SubKeyValue, Len(SubKeyValue))   ' Create/Modify Key Value

    If (rc <> ERROR_SUCCESS) Then GoTo CreateKeyError   ' Handle Error
    '------------------------------------------------------------
    '- Close Registry Key...
    '------------------------------------------------------------
    rc = RegCloseKey(hKey)                              ' Close Key
   
    UpdateKey = True                                    ' Return Success
    Exit Function                                       ' Exit
'------------------------------------------------------------
CreateKeyError:
'------------------------------------------------------------
    UpdateKey = False                                   ' Set Error Return Code
    rc = RegCloseKey(hKey)                              ' Attempt To Close Key
'------------------------------------------------------------
End Function
'------------------------------------------------------------

Public Function GetPath() As String
iReturn = GetKeyValue(HKEY_CURRENT_USER, sSoftwareKey, "ExportFilename", sExportPath, "")


End Function

Public Sub SetPath(sNewPath As String)
    iReturn = UpdateKey(HKEY_CURRENT_USER, sSoftwareKey, "ExportFilename", sNewPath)
End Sub

 

by: cybermoonlightPosted on 2001-12-03 at 02:39:30ID: 6663889

Instead of using the reg API's why not use the windows scripting host?
it is much simpler to use although obvioulsy less powerfull but provicdes the neccesarry methos for key retrival, modification, creation and deletion.

dim obWSH as object
set objWSH = createobject(scripting.shell)
then to change a value:

objWSH.writeKey "the path", "the value", "the type"

Regards,

 

by: ArkPosted on 2001-12-03 at 03:41:42ID: 6663936

Just a comment:
Should be
objWSH.RegWrite "the path", "the value", "the type"'[optional,no need if type is SZ_STRING, as in your case]

Cheers

 

by: BartonMPosted on 2001-12-03 at 07:13:08ID: 6664192

Why should you create a vb application? You can create a .reg file which you can manually change every time you need it.
Just create a text file and add the following text to it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\programme\settings]
"ExportFilename"="D:\\limjax\\ticker_priv.xls"

save this file as "anyfilename.reg".

now when you double-click this file, windows will automatically add the changes to the registry.

 

by: BartonMPosted on 2001-12-03 at 07:16:38ID: 6664199

Or go to the value in the registry editor and select the option "Export registry key" in the file menu. This will create the registry file for you

 

by: themrocPosted on 2001-12-06 at 01:46:13ID: 6668828

Thanks for the contribution,
the first solutiones appeared a little bit to adventures for my VB scills, so I tried the one from cybermoonlight and ART. I created a form with a command button to start the programme:


Private Sub com_filechange_Click()
Dim obWSH As Object
Set objWSH = CreateObject(scripting.Shell)

objWSH.RegWrite "HKEY_CURRENT_USER\Software\settings\ExportFilename", "D:\limjax\ticker.xls"
End Sub

______

but unfortuately I get a runtime error 424 "object required when I run the small routine. Before I setup the programme I downloaded scr55en.exe the exe file for "Windows Script 5.5" and installed it on the computer before restarting the machine. What did I wrong in the coding??

Some more explanations:
The path in the registry is:
HKEY_CURRENT_USER\Software\settings\
The value name is:
"ExportFilename"

The value data is:
D:\limjax\ticker.xls

 

by: ArkPosted on 2001-12-09 at 15:39:22ID: 6670224

Hi
Correct code:

Private Sub com_filechange_Click()
  Dim obWSH As Object
  Set obWSH = CreateObject("WScript.Shell")
  obWSH.RegWrite "HKCU\Software\settings\ExportFilename", "D:\limjax\ticker.xls"
  Set obWSH = Nothing
End Sub

Cheers

 

by: themrocPosted on 2001-12-10 at 01:18:18ID: 6670575

Despite the afford of cybermoonlight and all the others, in the end the hints from ARK got my small programme working. It works fine thanks all a lot!!!!!!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...