download certain tables from mysql server to particular location as csv files - excel

connect to mysql database.
should give user input which table to download from database.
selected table should get downloaded to particular location and save as a csv file. note csv name should be tablename.csv.
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = "localhost"
Database_Name = "testdb" ' Name of database
User = "root" 'id user or username
Password = "zxcasdQWE123" 'Password
SQLStr = "SELECT * FROM vector"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 Unicode Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";User=" & User & ";Password=" & Password & "; Option=3;"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
Dim ostream As Object
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
Set ostream = CreateObject("ADODB.Stream")
ostream.Open
'ostream.WriteText "hi, hello" & vbNewLine & "how, are" ' test input. not for any use
ostream.SaveToFile ("C:\Users\asus\Downloads\vector.csv")
ostream.Close
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
I have connected to my database and selected a table for eg and put into array. now i am struck with how to download that table as csv's. and make user input on which table to select from database.
Can anyone help me with it.

Create a new workbook, copy records to sheet using CopyFromRecordset and then save as CSV.
Option Explicit
Sub CreateCSV()
' logon credentials
Const Server_Name = "localhost"
Const Database_Name = "testdb" ' Name of database
Const User = "root" 'id user or username
Const Password = "zxcasdQWE123" 'Password
' connect
Dim Cn As Object, sCn As String, rs As Object
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 Unicode Driver}" & _
";Server=" & Server_Name & ";Database=" & Database_Name & _
";User=" & User & ";Password=" & Password & "; Option=3;"
' get list of tables
Dim arTbl, n As Long, sTbl As String, msg As String, u As Variant
Set rs = Cn.Execute("SHOW TABLES")
arTbl = rs.getrows()
For n = 1 To UBound(arTbl, 2)
msg = msg & n & ") " & arTbl(0, n - 1) & vbLf
Next
u = InputBox(msg, "Select Table")
' check user input is valid
If IsNumeric(u) Then
If u < 1 Or u > UBound(arTbl, 2) Then
MsgBox u & " is an invalid entry !", vbExclamation
Exit Sub
End If
Else
MsgBox u & " is an invalid entry !", vbExclamation
Exit Sub
End If
' selected table
sTbl = arTbl(0, u - 1)
' execute query
Dim wbCSV As Workbook, wb As Workbook, filename As String
Set rs = Cn.Execute("SELECT * FROM " & sTbl)
' create workbook, save as csv
Set wb = ThisWorkbook
Set wbCSV = Workbooks.Add(1)
filename = wb.Path & "\" & sTbl & ".csv"
With wbCSV.Sheets(1)
' header
For n = 1 To rs.Fields.Count
.Cells(1, n) = rs.Fields(n - 1).Name
Next
' data
.Range("A2").CopyFromRecordset rs
n = .Cells(.Rows.Count, "A").End(xlUp).Row
.SaveAs filename, xlCSV
wbCSV.Close savechanges:=False
End With
MsgBox n - 1 & " rows exported to " & filename, vbInformation
End Sub

Related

Updating records in Access table using excel VBA

UPDATED QUESTION:
I have Update sheet, this sheet contains unique ID that matched the access database ID, I'm trying to update the fields using excel values in "Update" sheet.
The ID is in the Column A the rest of the fields are stored from Column B to R. I'm trying to achieve the below, As follows:
Update the record(values from Column B to R) if Column A (ID) matched existing Access database ID. Then add text in Column S "Updated"
If the Column A (ID) did not found any match in the existing Access database ID, Then add text in Column S "ID NOT FOUND"
Loop to next value
So far, I have the below Sub for Update and Function for Existing ID (Import_Update Module), but I'm getting this error.
Sub Update_DB()
Dim dbPath As String
Dim lastRow As Long
Dim exportedRowCnt As Long
Dim NotexportedRowCnt As Long
Dim qry As String
Dim ID As String
'add error handling
On Error GoTo exitSub
'Check for data
If Worksheets("Update").Range("A2").Value = "" Then
MsgBox "Add the data that you want to send to MS Access"
Exit Sub
End If
'Variables for file path
dbPath = Worksheets("Home").Range("P4").Value '"W:\Edward\_Connection\Database.accdb" '##> This was wrong before pointing to I3
If Not FileExists(dbPath) Then
MsgBox "The Database file doesn't exist! Kindly correct first"
Exit Sub
End If
'find las last row of data
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim cnx As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
On Error GoTo errHandler
'Initialise the collection class variable
Set cnx = New ADODB.Connection
'Connection class is equipped with a —method— named Open
cnx.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'ADO library is equipped with a class named Recordset
Set rst = New ADODB.Recordset 'assign memory to the recordset
'##> ID and SQL Query
ID = Range("A" & lastRow).Value
qry = "SELECT * FROM f_SD WHERE ID = '" & ID & "'"
'ConnectionString Open '—-5 aguments—-
rst.Open qry, ActiveConnection:=cnx, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
'add the values to it
'Wait Cursor
Application.Cursor = xlWait
'Pause Screen Update
Application.ScreenUpdating = False
'##> Set exportedRowCnt to 0 first
UpdatedRowCnt = 0
IDnotFoundRowCnt = 0
If rst.EOF And rst.BOF Then
'Close the recordet and the connection.
rst.Close
cnx.Close
'clear memory
Set rst = Nothing
Set cnx = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'In case of an empty recordset display an error.
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
For nRow = 2 To lastRow
'##> Check if the Row has already been imported?
'##> Let's suppose Data is on Column B to R.
'If it is then continue update records
If IdExists(cnx, Range("A" & nRow).Value) Then
With rst
For nCol = 1 To 18
rst.Fields(Cells(1, nCol).Value2) = Cells(nRow, nCol).Value 'Using the Excel Sheet Column Heading
Next nCol
Range("S" & nRow).Value2 = "Updated"
UpdatedRowCnt = UpdatedRowCnt + 1
rst.Update
End With
Else
'##>Update the Status on Column S when ID NOT FOUND
Range("S" & nRow).Value2 = "ID NOT FOUND"
'Increment exportedRowCnt
IDnotFoundRowCnt = IDnotFoundRowCnt + 1
End If
Next nRow
'close the recordset
rst.Close
' Close the connection
cnx.Close
'clear memory
Set rst = Nothing
Set cnx = Nothing
If UpdatedRowCnt > 0 Or IDnotFoundRowCnt > 0 Then
'communicate with the user
MsgBox UpdatedRowCnt & " Drawing(s) Updated " & vbCrLf & _
IDnotFoundRowCnt & " Drawing(s) IDs Not Found"
End If
'Update the sheet
Application.ScreenUpdating = True
exitSub:
'Restore Default Cursor
Application.Cursor = xlDefault
'Update the sheet
Application.ScreenUpdating = True
Exit Sub
errHandler:
'clear memory
Set rst = Nothing
Set cnx = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Update_DB"
Resume exitSub
End Sub
Function to Check if the ID Exists
Function IdExists(cnx As ADODB.Connection, sId As String) As Boolean
'Set IdExists as False and change to true if the ID exists already
IdExists = False
'Change the Error handler now
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim cmd As ADODB.Command 'dim the ADO command class
On Error GoTo errHandler
'Sql For search
Dim sSql As String
sSql = "SELECT Count(PhoneList.ID) AS IDCnt FROM PhoneList WHERE (PhoneList.ID='" & sId & "')"
'Execute command and collect it into a Recordset
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnx
cmd.CommandText = sSql
'ADO library is equipped with a class named Recordset
Set rst = cmd.Execute 'New ADODB.Recordset 'assign memory to the recordset
'Read First RST
rst.MoveFirst
'If rst returns a value then ID already exists
If rst.Fields(0) > 0 Then
IdExists = True
End If
'close the recordset
rst.Close
'clear memory
Set rst = Nothing
exitFunction:
Exit Function
errHandler:
'clear memory
Set rst = Nothing
MsgBox "Error " & Err.Number & " :" & Err.Description
End Function
My below code is working fine. I tried to address your above three points in a different way.
##########################
IMPORTANT
1) I have removed your other validations; you can add them back.
2) DB path has been hard coded, you can set it to get from a cells again
3) My DB has only two fields (1) ID and (2) UserName; you will have obtain your other variables and update the UPDATE query.
Below is the code which is working fine to meet your all 3 requests...Let me know how it goes...
Tschüss :)
Sub UpdateDb()
'Creating Variable for db connection
Dim sSQL As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test\db.accdb;"
Dim a, PID
'a is the row counter, as it seems your data rows start from 2 I have set it to 2
a = 2
'Define variable for the values from Column B to R. You can always add the direct ceel reference to the SQL also but it will be messy.
'I have used only one filed as UserName and so one variable in column B, you need to keep adding to below and them to the SQL query for othe variables
Dim NewUserName
'########Strating to read through all the records untill you reach a empty column.
While VBA.Trim(Sheet19.Cells(a, 1)) <> "" ' It's always good to refer to a sheet by it's sheet number, bcos you have the fleibility of changing the display name later.
'Above I have used VBA.Trim to ignore if there are any cells with spaces involved. Also used VBA pre so that code will be supported in many versions of Excel.
'Assigning the ID to a variable to be used in future queries
PID = VBA.Trim(Sheet19.Cells(a, 1))
'SQL to obtain data relevatn to given ID on the column. I have cnsidered this ID as a text
sSQL = "SELECT ID FROM PhoneList WHERE ID='" & PID & "';"
Set rs = New ADODB.Recordset
rs.Open sSQL, cn
If rs.EOF Then
'If the record set is empty
'Updating the sheet with the status
Sheet19.Cells(a, 19) = "ID NOT FOUND"
'Here if you want to add the missing ID that also can be done by adding the query and executing it.
Else
'If the record found
NewUserName = VBA.Trim(Sheet19.Cells(a, 2))
sSQL = "UPDATE PhoneList SET UserName ='" & NewUserName & "' WHERE ID='" & PID & "';"
cn.Execute (sSQL)
'Updating the sheet with the status
Sheet19.Cells(a, 19) = "Updated"
End If
'Add one to move to the next row of the excel sheet
a = a + 1
Wend
cn.Close
Set cn = Nothing
End Sub
You need to put the query inside the loop
Option Explicit
Sub Update_DB_1()
Dim cnx As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim qry As String, id As String, sFilePath As String
Dim lastRow As Long, nRow As Long, nCol As Long, count As Long
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Update")
lastRow = ws.Cells(Rows.count, 1).End(xlUp).Row
sFilePath = wb.Worksheets("Home").Range("P4").Value
cnx.open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFilePath
count = 0
For nRow = 2 To lastRow
id = Trim(ws.Cells(nRow, 1))
qry = "SELECT * FROM f_SD WHERE ID = '" & id & "'"
Debug.Print qry
rst.open qry, cnx, adOpenKeyset, adLockOptimistic
If rst.RecordCount > 0 Then
' Update RecordSet using the Column Heading
For nCol = 2 To 9
rst.fields(Cells(1, nCol).Value2) = Cells(nRow, nCol).Value
Next nCol
rst.Update
count = count + 1
ws.Range("S" & nRow).Value2 = "Updated"
Else
ws.Range("S" & nRow).Value2 = "ID NOT FOUND"
End If
rst.Close
Next nRow
cnx.Close
Set rst = Nothing
Set cnx = Nothing
MsgBox count & " records updated", vbInformation
End Sub

Excel function with ADODB connection string to Access database

I've created below Excel function which connects to an access database with ADODB (approx 10k lines).
It generally works but there are two main issues:
It is unreliable: often it returns 0 while the result should be different
It is definitely slow
Any suggestion on how to improve?
Public Function TotaleSQL(Cat As String, SubCat As String, Anno As Integer) As Long
On Error Resume Next
Dim cn As Object, rs As Object, output As String, sql As String
Dim src As String
Dim Total As Long
Dim CatLong As String
src = "Z:\Report.accdb"
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & src & ";Persist Security Info=False"
.Open
End With
'---Run the SQL SELECT Query---
CatLong = "'" & Cat & ":" & SubCat & "'"
sql = "SELECT Report.Withdrawal, Report.Deposit, Report.Category, Report.Date FROM Report WHERE (((Report.Category)=" & CatLong & ") AND ((Year([date]))=" & Anno & "));"
'sql = "SELECT * FROM [Sheet1$]"
Set rs = cn.Execute(sql)
Total = 0
Do
Total = Total + Val(rs(1) & "") - Val(rs(0) & "")
rs.Movenext
Loop Until rs.EOF
'---Clean up---
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
TotaleSQL = Total
End Function
If Cat, SubCat or Anno are user inputs it is more secure to use parameters in your query. For example
Public Function TotaleSQL(Cat As String, SubCat As String, Anno As Integer)
Const DATABASE = "Z:\Report.accdb"
Const TABLE_NAME = "Report"
Const SQL = " SELECT SUM(iif(Deposit is null,0,Deposit) " & _
" - iif(Withdrawal is null,0,Withdrawal)) " & _
" FROM " & TABLE_NAME & _
" WHERE Category = ? " & _
" AND YEAR(ddate)= ? "
Dim cn As Object, cmd As Object, rs As Object
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & DATABASE & ";Persist Security Info=False"
.Open
End With
' create command
Set cmd = CreateObject("ADODB.Command")
With cmd
.ActiveConnection = cn
.CommandText = SQL
.CommandType = 1 'adCmdText
.Parameters.Append .CreateParameter("P1", 200, 1, 50) ' 1=adParamInput 200=adVarChar
.Parameters.Append .CreateParameter("P2", 3, 1) ' 3=adInteger
End With
' execute with parameters
With cmd
.Parameters(0).Value = Cat & ":" & SubCat
.Parameters(1).Value = Anno
Set rs = .Execute
End With
TotaleSQL = rs(0)
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
Set cmd = Nothing
End Function
Sub test()
Debug.Print TotaleSQL("Cat", "SubCat", 2020)
End Sub

Application Connect Excel sheet to Access

I am stuck at below mentioned situation guide me. I have one user form i made in excel . i can try to perform crud i have completed insert. i can try to update or delete not working please give me some idea.
this is my insert code it is properly working
insert:-
Private Sub CommandButton1_Click()
Dim cn As Object
Dim strQuery As String
Dim Name As String
Dim City As String
Dim myDB As String
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Initialize Variables
Name = Me.TextBox1.Value
City = Me.TextBox2.Value
Dept = Me.ComboBox1.Value
myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
'Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases
.ConnectionString = myDB
.Open
MsgBox "con created"
End With
strQuery = "INSERT INTO emp ([Name], [City],[Dept]) " & _
"VALUES (""" & Name & """, """ & City & """,""" & Dept & """); "
MsgBox "success fully insert"
cn.Execute strQuery
cn.Close
Set cn = Nothing
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub
update code:-
Dim cn As Object
Dim strQuery As String
Dim Name As String
Dim City As String
Dim myDB As String
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Initialize Variables
' Name = Me.TextBox1.Value
' City = Me.TextBox2.Value
' Dept = Me.ComboBox1.Value
myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
'Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases
.ConnectionString = myDB
.Open
MsgBox "con created"
End With
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"
MsgBox "success fully insert"
cn.Execute strQuery
cn.Close
Set cn = Nothing
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub
Your line
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"
is attempting to update all lines in the emp table with those values. I suspect you only want to update one line. You need to add a WHERE clause to specify which line.
EDIT: Just noticed there's a syntax error in that line as well. It should read
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "', [City]='" & TextBox2.Value & "',[Dept]='" & Me.ComboBox1.Value & "' Where "
and then should finish with your where clause

Excel data to Access DB - Get: Operation must use an updateable query Error

I am working on an Excel application which allows users to enter hours work through userforms and info is stored in a Access DB. I am new to excel and access connections. I am able to connect to the database but record is not saved/created due to a run-time error at the .Update command.
Run-Time Error '-2147467259 (80004005)': Operation must use an updatable query.
I have searched and searched and can't find a solution to this problem. I hope someone is able to help. (code below)
Sub Export_Data_Access_TI1()
Dim dbPath As String
Dim x As Long, i As Long
Dim nextrow As Long
Dim user As String
Dim NewSht As Worksheet
Dim strQuery As String
Dim recDate As String
Dim Week_Of As String
user = Sheet1.Range("A1").Text
On Error GoTo ErrHandler:
'Variables for file path and last row of data
dbPath = "H:\PROJECTS\CAI_DOT-Time Tracker\CAI_EMP_SignIn_Database.accdb"
nextrow = Cells(Rows.Count, 1).End(xlUp).Row
'Initialise the collection class variable
Set cnn = New ADODB.Connection
'Check for data
If Sheets(user).Range("A2").Value = "" Then
MsgBox " There is no data to send to MS Access"
Exit Sub
End If
cnn.Mode = adModeReadWrite
'cnn.Mode = adModeShareDenyNone
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
Set rst = New ADODB.Recordset 'assign memory to the recordset
rst.CursorLocation = adUseClient
rst.Open Source:="DATA", ActiveConnection:=cnn, _
CursorType:=adOpenKeyset, LockType:=adLockPessimistic, _
Options:=adCmdTable
'rst.Supports (adAddNew)
x = 2 'the start row in the worksheet
Do While Len(Sheets(user).Range("A" & x).Formula) > 0
With rst
.AddNew 'create a new record
.Fields("Date") = ActiveWorkbook.Sheets(user).Range("A" & x).Value
.Fields("Week_Of") = Sheets(user).Range("B" & x).Value
.Fields("Month") = Sheets(user).Range("C" & x).Value
.Fields("Name") = Sheets(user).Range("D" & x).Value
.Fields("Time_In") = Sheets(user).Range("E" & x).Value
.Fields("Time_Out") = Sheets(user).Range("F" & x).Value
.Fields("Time_In2") = Sheets(user).Range("G" & x).Value
.Fields("Time_Out2") = Sheets(user).Range("H" & x).Value
.Fields("Group") = Sheets(user).Range("I" & x).Value
.Fields("UniqueID") = Sheets(user).Range("J" & x).Value
.Fields("Comments") = Sheets(user).Range("K" & x).Value
.Update 'stores the new record
End With
x = x + 1 'next row
Loop
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
'communicate with the user
MsgBox " The data has been successfully sent to the access database"
'Update the sheet
Application.ScreenUpdating = True
'Clear the data
'Sheets(user).Range("A1:K1000").ClearContents
On Error GoTo 0
Exit Sub
ErrHandler:
'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
End Sub
As I understand, DATA is a query in the remote accdb. If so, it should be updateable. See, for example this: Why is my query not updateable? for criterias. If this is a table, check if you have read-write rights on accdb and the file has no read-only attribute.

Issue with VBA Script in Excel to pull LDAP Query

I am currently having an issue with VBA Script that I have written to pull some LDAP information from Active Directory. However, I have came to a break in the code at GetAdsProp.
There is a listing to refernce "o" in LDAP as Business Unit. I need to pull that said name from LDAP Query "o".
Here is the code that I am working with:
Sub Update_List()
Set a = Application.Selection
For Each b In a.Rows
Number = b.Row
letter = b.Column
If Range("A" & Number).Value <> "" Then
corpID = Range("A" & Number).Value
Cells.Range("E" & Number).Value = GetAdsProp("samAccountName", corpID, "Name")
Cells.Range("F" & Number).Value = GetCNName(GetAdsProp("samAccountName", corpID, "Manager"))
Cells.Range("G" & Number).Value = GetCNName(GetAdsProp("samAccountName", corpID, "o"))
End If
Next
End Sub
Function GetAdsProp(ByVal SearchField As String, ByVal SearchString As String, ByVal ReturnField As String) As String
' Get the domain string ("dc=domain, dc=local")
Dim strDomain As String
strDomain = GetObject("LDAP://rootDSE").Get("defaultNamingContext")
' ADODB Connection to AD
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
' Connection
Dim objCommand As ADODB.Command
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
' Search the AD recursively, starting at root of the domain
objCommand.CommandText = _
"<LDAP://" & strDomain & ">;(&(objectCategory=User)" & _
"(" & SearchField & "=" & SearchString & "));" & SearchField & "," & ReturnField & ";subtree"
' RecordSet
Dim objRecordSet As ADODB.Recordset
Set objRecordSet = objCommand.Execute
If objRecordSet.RecordCount = 0 Then
GetAdsProp = "not found" ' no records returned
Else
GetAdsProp = objRecordSet.Fields(ReturnField) ' return value
End If
' Close connection
objConnection.Close
' Cleanup
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing
End Function
Function GetCNName(ByVal CNInput As String) As String
' GetCNName = Regex.Replace(CNInput, "CN=[^,]*,* *", "")
Set RE = CreateObject("vbscript.regexp")
' Get the first part of the CN string up to the second comma
RE.Pattern = "^CN=([^,]*,){2}"
Set foo = RE.Execute(CNInput)
' Get the matched part
CN = ""
For Each Match In foo
If CN = "" Then
CN = Match.Value
End If
Next
' Replace the first bit of text
RE.Pattern = "^CN="
CN = RE.Replace(CN, "")
' Replace the last comma
RE.Pattern = ",$"
CN = RE.Replace(CN, "")
' Replace the slash
RE.Pattern = "\\"
CN = RE.Replace(CN, "")
GetCNName = CN
End Function
Here is the error that I am getting:
Visual Basic Error
Get AdsProp Line issue
Any help would be greatly appreciated.
Thank You.

Resources