2017-11-15 13 views
0

저희 회사의 다른 공급 업체 조직에 대한 AD 사용자의 CSV 파일 목록을 생성하는 스크립트를 작성했습니다. 이제 C :에서 저장 한 다른 Excel 파일의 두 번째 탭 (워크 시트)에 아래 스크립트 출력을 추가하고 싶습니다.VB 스크립트가 다른 워크 시트에 스크립트 출력 묻기

다른 Excel 파일의 두 번째 탭 (워크 시트)에 출력되도록 인쇄 할 때 다음 코드를 추가했지만 동일한 오류가 여러 번 발생합니다.

Option Explicit 
Dim xL 
Dim Targetbook 
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx") 
Dim Targetsheet 
Set Targetsheet = targetbook.worksheets("IM AD users") 
Dim t 
Set t = targetsheet.range("a1") 

하지만 위의 코드 조각을 추가하고 코드를 실행할 때 여러 개의 VBScript를 컴파일 오류를 얻고있다 - 다음과 같이 코드입니다. 내가 여기서하고있는 실수는 무엇입니까? 또는 count = count +1 명령문을 추가하여 다른 통합 문서의 두 번째 워크 시트에 결과를 추가 할 수 있습니까? 나는 일종의 새롭고 혼란 스럽습니다. 코드의

처음 몇 줄은 어쩌면해야한다 : 그 유입 외에도

Option Explicit 
Dim xL 
Set xl = CreateObject("Excel.Application") 
Dim Targetbook 
Set Targetbook = xl.Workbooks.Open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx") 
Dim targetsheet 
targetbook.Sheets("IM AD users").Select 
Set targetsheet = targetbook.ActiveSheet '<<<i added SET here 

내가 볼 수

Option Explicit 
Dim xL 
Dim Targetbook 
Set Targetbook = xl.workbooks.open("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx") 
Dim Targetsheet 
Set Targetsheet = targetbook.worksheets("IM AD users") 
Dim t 
Set t = targetsheet.range("a1") 

Dim objConnection,objCommand,objRecordSet,objUser,ObjFSO, InitFSO,objdialog,thisday,intreturn,OutputFile,myprompt 
Dim intCounter,strfname,strDN,arrPath,stroutput,objoutput,Account_locked,Objclass,ObjMail 
Dim StrEmpType,IntUAC,UserStatus,slogin,Last_Logon_timestamp,Last_Login,Last_pwd_changed,PWD_Never_Expire,objLastLogon,intLastLogonTime,intLastLogon,User_must_change_pwd 



Dim objShell 
Dim strFileName 
Dim strFilePath 
Dim objFile 
Dim manager,manager1,manager2,IMSite,IMSite1,IMSite2,count 

Const ADS_SCOPE_SUBTREE = 2 
Const ForWriting = 2 
Const ADS_UF_ACCOUNTDISABLE = 2 
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000 
Const ADS_UF_PASSWD_NOTREQD = &H0020 
Const ADS_UF_PASSWORD_EXPIRED = 8388608 
Const ADS_UF_LOCKOUT= 16 

' Declare Option Constants 
'------------------------ 
Const BIF_EDITBOX = &H10 
Const BIF_NONEWFOLDER = &H0200 
Const BIF_RETURNONLYFSDIRS = &H1 

Dim strprompt, intoptions,strroot,strfolderpath 

' Setup connection to AD 
'------------------------ 
Set objConnection = CreateObject("ADODB.Connection") 
Set objCommand = CreateObject("ADODB.Command") 
objConnection.Provider = "ADsDSOObject" 
objConnection.Open "Active Directory Provider" 
Set objCommand.ActiveConnection = objConnection 






' Specify the output file. 
'----------------------------- 

Msgbox " This script will generate a list of all IM AD users that are into the IM OU in the imaje.intra domain and that are enabled." & vbnewline & vbnewline _ 
    & "You will be prompted to enter the location where to store the output file." _ 
    & vbnewline & vbnewline & " Just browse the folder where you want to save it " _ 
    & vbnewline & vbnewline & " You will be notified when the script will be completed . Press OK to continue" 



' Generate the output filename with the date 
'------------------------------------------- 
thisday=Year(Date) & Right("0" & Month(Date),2) & Right("0" & Day(Date),2) 


strPrompt = "Please select the folder where to store the final output file." 
intOptions = BIF_RETURNONLYFSDIRS + BIF_EDITBOX + BIF_NONEWFOLDER 

' Return the path, e.g. C:\ 
strFolderPath = Browse4Folder(strPrompt, intOptions, "") 

OutputFile = strFolderPath & "\List_IM_AD_users_" & thisday & ".csv" 

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objoutput = objFSO.CreateTextFile(OutputFile) 


Msgbox " Press OK to start extracting Active Directory information for IM Users into " & OutputFile & vbnewline & vbnewline _ 
    & " You'll be notified when the script will be completed !" 


' Set paging file higher to accommodate lots of AD records 
'------------------------------------------------------------- 

objCommand.Properties("Page Size") = 40000 
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

'Prepare the LDAP command 
'-------------------------- 

objCommand.CommandText = "SELECT AdsPath FROM 'LDAP://OU=IM,OU=MIUsers,OU=MI,DC=Imaje,DC=intra' WHERE objectCategory='user'" 
Set objRecordSet = objCommand.Execute 
objRecordSet.MoveFirst 

' Read the Entire AD domain for objectCategory=user and write the various fields into the output file 
'----------------------------------------------------------------------------------------------------- 
objOutput.Write "SamAccountName;GivenName;sn;DisplayName;E-mail @;IM Site;Exists in IM list;IM location;Title;Country;Manager;employeeID;Account locked;Last Logon;LastLogon timestamp;Pwd Never Expires;Last PWD Change;User_must_change_pwd;User creation date;User Change Date;Description;DN" & vbcrlf 

count=1 

Do Until objRecordSet.EOF 
    Userstatus="Enabled" 
    Set objUser = GetObject(objRecordSet.Fields("AdsPath").Value) 

' Get status of the User (disabled or not , pwd required or Not , User must change pwd) 
'------------------------------------------------------------------------------------------- 
    intUAC=ObjUser.userAccountControl 
    If intUAC AND ADS_UF_ACCOUNTDISABLE Then 
     Userstatus="Disabled" 
    End If 

    If intUAC AND ADS_UF_DONT_EXPIRE_PASSWD Then 
     PWD_Never_Expire="Yes" 
    Else 
     pwd_never_expire="No" 
    End If 

    If intUAC AND ADS_UF_PASSWORD_EXPIRED Then 
     User_must_change_pwd="Yes" 
    Else 
     User_must_change_pwd="No" 
    End If 

    If intUAC AND ADS_UF_LOCKOUT Then 
     Account_locked="Yes" 
    Else 
     Account_locked="No" 
    End If 



' Get LastLogonTimestamp , LastLogon, LastPwdChange of the User 
'------------------------------------------------------------------ 

    On Error Resume Next 

    Set objLastLogon = objUser.Get("lastLogonTimestamp") 

    intLastLogonTime = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart 
    intLastLogonTime = intLastLogonTime/(60 * 10000000) 
    intLastLogonTime = intLastLogonTime/1440 

    Last_Logon_timestamp=intLastLogonTime + #1/1/1601# 

    Set objLastLogon = objUser.Get("lastLogon") 

    intLastLogon = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart 
    intLastLogon = intLastLogon/(60 * 10000000) 
    intLastLogon = intLastLogon/1440 

    Last_Login=intLastLogon + #1/1/1601# 

    On Error Goto 0 

    On Error Resume Next 

    sLogin = objUser.passwordLastChanged 
    If Err = 0 Then 
      Last_pwd_changed=sLogin 
     Else 
      Last_pwd_changed="Never" 
     End If 

    On Error Goto 0 

    ObjClass = objUser.Class 

    ObjMail = objUser.Mail 
    manager = "" 
    IMSite="" 

    If ObjClass = "user" and userstatus = "Enabled" then 
     On Error Resume Next 
     manager1= split(objUser.Manager,",") 
     manager = manager1(0) 
     manager2=split(manager,"=") 
     manager = manager2(1) 

     IMSite1 = InStr(ObjUser.distinguishedName,",OU=IM") 
     IMSite2 = Mid (ObjUser.distinguishedName,IMSite1-12,12) 
     IMSite1 = split(IMSite2,"=") 
     IMSite = IMSite1(1) 

     count=count + 1 


     objOutput.Write objUser.samaccountname &";" & objUser.GivenName &";" & objUser.sn &";" & objUser.DisplayName &";" & ObjMail & ";" & IMSite & _ 
     ";=IFERROR(IF(VLOOKUP(E" & count & ",'IM employees'!C:C,1,FALSE)=E" & count & ",""Yes""),""No"")" & ";=IF(G" & count & "=""Yes"",VLOOKUP(E" & _ 
     count & ",'IM employees'!C:D,2,FALSE),""Missing"")" & ";" &ObjUser.Title & ";" & ObjUser.Co & ";" & Manager &";" & objUser.employeeID & ";" & _ 
     Account_locked & ";" & last_Login & ";" & last_Logon_timestamp & ";"& pwd_never_expire & ";"& Last_pwd_Changed & ";" _ 
     & User_must_change_pwd & ";" & objUser.whenCreated & ";" & objUser.whenChanged & ";" & objUser.description &";" & objUser.distinguishedName &";" & vbcrlf 

    End If 

' Next record in recordset 
'------------------------------ 
    objRecordSet.MoveNext 


Loop 

Msgbox " Script is completed ! The file " & OutputFile & " is now ready !! " 

'End Script 



Function Browse4Folder(strPrompt, intOptions, strRoot) 
    Dim objFolder, objFolderItem, objShell 
    Set objShell = CreateObject("Shell.Application") 
    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot) 
    If (objFolder Is Nothing) Then 
     Browse4Folder = "" 
    Else 
     Set objFolderItem = objFolder.Self 
     Browse4Folder = objFolderItem.Path  
     Set objFolderItem = Nothing 
     Set objFolder = Nothing 
    End If 
    Set objShell = Nothing 
End Function 

답변

0

하나의 잠재적 인 문제는 먼저 엑셀의 보류를 받고되지 않는다는 것입니다 데이터는 꽤 직설적입니다.

Dim currentRow : currentRow = 1 

Function RecordData (username,companyCode) 
    targetsheet.Cells(currentRow,1).Value = companyCode 
    targetsheet.Cells(currentRow,2).Value = username 
    currentRow = currentRow + 1 
End Function 

다음은 데이터가있는 요일 u는 원하는 : 도움을

'alerts need to be disabled so that you don't get warnings about saving over the file etc. (excel pop ups) 
'ALERTS MUST BE TURNED ON AGAIN IMMEDIATELY AS THIS IS A GLOBAL SETTING FOR EXCEL 
' - i.e. users will not get warnings about unsaved files etc. when quitting excel normally' 
xl.DisplayAlerts = false 
targetbook.SaveAs("C:\Users\achowdhury\Desktop\Projects\Project automation\IM controls\Iuc.xlsx") 
xl.DisplayAlerts = true 

'close workbook now it has been saved - there should be no pop ups' 
targetbook.Close() 

'release references and close excel' 
set targetbook = nothing 
set targetsheet = nothing 

xl.Quit() 

set xl = Nothing 
+0

많은 감사 : 또한 파일을 저장하고 닫습니다해야합니다

RecordData ("2000","bobbyj") 

. 당신은 친절하게도 내 응답을 볼 수 있습니다 : - https://pastebin.com/ZeK8JiVt –

+0

@AvikChowdhury 당신은'targetsheet.Cells (row, column) .Value = something'을 사용하여 파일에 데이터를 써야합니다. .. 내가 타겟 시트의 할당에서 SET를 놓친 것 같아요 .. 수정 된 코드를 참조하십시오. 이 모든 작품이 작동한다면 당신은 아마도 이것을 대답으로 표시하고 다른 질문을 게시해야한다고 생각합니다. 이상적으로는 질문이 구체적이어야합니다. – gordatron

+0

감사합니다. @ gordatron. –