[英]Importing variables from TXT files to a Word document
Long story, thanks for reading :)长篇大论,感谢阅读:)
I'm trying to automate analyzing an AD export.我正在尝试自动分析 AD 导出。 I send a customer PowerShell scripts to export AD data to CSV.我向客户发送 PowerShell 脚本以将 AD 数据导出为 CSV。 They send me the CSV files, I import those into an analytic tool called WeGalvanice ACL (ACL for short).他们给我发送了 CSV 文件,我将它们导入到一个名为 WeGalvanice ACL(简称 ACL)的分析工具中。 Within ACL I am able to filter/match/compare and whatever I need doing.在 ACL 中,我能够过滤/匹配/比较以及我需要做的任何事情。
So far all good.到目前为止一切都很好。 Now I want to use those results and put them in a .docx file, and here comes trouble.现在我想使用这些结果并将它们放在一个 .docx 文件中,但麻烦来了。 ACL cant export to docx, only xlsx/txt/csv/html/json/del. ACL 不能导出到 docx,只能导出 xlsx/txt/csv/html/json/del。
Ok well we can work around that (or so i thought), I made a template.docx
within that template.docx
I wrote the placeholders like %certainvariable%
.确定好我们可以变通解决(或所以我想),我做了一个template.docx
是内template.docx
我写的像占位符%certainvariable%
Within ACL I created a command to write all variables I need to files called %variablename%.txt
and within the txt is the value I need.在 ACL 中,我创建了一个命令将我需要的所有变量写入名为%variablename%.txt
文件中,txt 中是我需要的值。
For example:例如:
ACL creates disabledusers.txt
. ACL 创建disabledusers.txt
。 If you open the txt it only shows 10, meaning we got 10 disabled users.如果你打开 txt 它只显示 10,这意味着我们有 10 个禁用用户。
Then I tried to create a VBA macro to import the txt files and use the contained values to replace the according %...%
text within the Word document.然后我尝试创建一个 VBA 宏来导入 txt 文件并使用包含的值替换 Word 文档中相应的%...%
文本。
This all looked to go smoothly until I noticed that after running the script I got 20
followed by that box that meanings "I have no clue how to display this char".这一切看起来都很顺利,直到我注意到在运行脚本后我得到了20
后跟那个框,意思是“我不知道如何显示这个字符”。
Prior to running the script:在运行脚本之前:
After running the script:运行脚本后:
picture of .txt content that i import:我导入的 .txt 内容的图片:
And last but not least the VBS code im using from word Macro manager (for convenience I only uploaded 1 import-and-replace job, but in my script I just copied this 30 times for each file and variable):最后但并非最不重要的是,我使用 word 宏管理器中的 VBS 代码(为方便起见,我只上传了 1 个导入和替换作业,但在我的脚本中,我只是为每个文件和变量复制了 30 次):
Sub ACL()
' ACL Macro
FilePath = "local folderpath\date.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
new_date = Input(LOF(TextFile), TextFile)
old_date = "%date%"
Close TextFile
With ActiveDocument.Content.Find
.Forward = True
.Wrap = wdFindStop
.Execute findtext:=old_date, replacewith:=new_date, Replace:=wdReplaceAll
End With
End Sub
When I open the date.txt
manualy and remove the second line then it all seems to work.当我date.txt
打开date.txt
并删除第二行时,它似乎一切正常。 But I want it automated.但我希望它自动化。 ;) ;)
I tried我试过
split textfile,/n
and split new_date,/n
both with \\n\\r
and \\r
to no avail.添加split textfile,/n
和split new_date,/n
都与\\n\\r
和\\r
无济于事。I'm open for suggestions on any programming language, (im terrible at them all) ill just queue everything in the right order to make it work ;)我对任何编程语言的建议持开放态度(我对它们都很糟糕)我只是按照正确的顺序将所有内容排队以使其工作;)
thanks in advance everyone!提前谢谢大家! and of course ask away if you need more info当然,如果您需要更多信息,请询问
Update thanks to Tomalak i got the principle working:感谢 Tomalak 的更新,我得到了原理:
' removes CR & LF from the end of a string (not pretty but gets the job done)
Function TrimRight(InputStr As String) As String
While Right(InputStr, 1) = vbCr Or Right(InputStr, 1) = vbLf
InputStr = Left(InputStr, Len(InputStr) - 1)
Wend
TrimRight = Trim(InputStr)
End Function
' reads any text file and returns the content as-is
Function ReadFile(FilePath As String) As String
Dim filenum As Integer
If Dir(FilePath) > "" Then
filenum = FreeFile
Open FilePath For Input As filenum
ReadFile = Input(LOF(filenum), filenum)
Close filenum
Else
Debug.Print "File not found: " & FilePath
End If
End Function
' replaces all instances of a single word in the given document
Sub ReplaceAll(oldValue As String, newValue As String, doc As Document)
With doc.Content.Find
.Forward = True
.Wrap = wdFindStop
.Execute findtext:=oldValue, replacewith:=newValue, Replace:=wdReplaceAll
End With
End Sub
Sub ReplaceAllVariables()
Dim variables As Variant, variable As Variant
Dim placeholder As String, realValue As String
variables = Split("customer,c_adgroup,c_adgroup_Cannot_change_PW,c_adgroup_disabled,c_adgroup_enabled,c_adgroup_expire_and_disabled,c_adgroup_LockedOut,c_adgroup_Locked_and_disabled,c_adgroup_loginx,c_adgroup_loginx_disabled,c_adgroup_nolastpasswordset,c_adgroup_nologondate,c_adgroup_PWRQ_and_disabled,c_adgroup_PWx,c_adgroup_PWx_and_disabled,c_adgroup_PW_and_disabled,c_adgroup_PW_and_enabled,c_adgroup_PWRQ_and_enabled ,c_adgroup_PW_not_required,c_adgroup_PW_no_expire,c_adgroup_loginx_and_enabled,c_adusers_f_Cannot_change_PW,c_adusers_f_disabled,c_adusers_f_enabled,c_adusers_f_expire_and_disabled,c_adusers_f_LockedOut,c_adusers_f_Locked_and_disabled,c_adusers_f_loginx,c_adusers_f_loginx_disabled,c_adusers_f_nolastpasswordset,c_adusers_f_nologondate,c_adusers_f_PWRQ_and_disabled,c_adusers_f_PWx,c_adusers_f_PWx_and_disabled,c_adusers_f_PW_and_disabled,c_adusers_f_PW_not_required,c_adusers_f_PW_no_expire,c_adusers_f_loginx_and_enabled,date,c_adusers_f_PW_and_enabled,lastlogon", ",")
For Each variable In variables
placeholder = "%" & variable & "%"
realValue = ReadFile("C:\Users\jerryw\Documents\Klanten\ACL\AD analyse\var\" & variable & ".txt")
realValue = TrimRight(realValue)
ReplaceAll placeholder, realValue, ActiveDocument
Next
End Sub
The problem seems to be the newline (CRLF).问题似乎是换行符(CRLF)。 You have to get rid of it.你必须摆脱它。
And while we are at it, let's also get rid of the "I've copied that code 30 times" bit, that's a horrible way to solve this problem.当我们在做的时候,让我们也摆脱“我已经复制了 30 次代码”这一点,这是解决这个问题的一种可怕的方式。 Loops are better.循环更好。
Helpers:帮手:
' removes CR & LF from the end of a string (not pretty but gets the job done)
Function TrimRight(InputStr As String) As String
While Right(InputStr, 1) = vbCr Or Right(InputStr, 1) = vbLf
InputStr = Left(InputStr, Len(InputStr) - 1)
Wend
TrimRight = Trim(InputStr)
End Function
' reads any text file and returns the content as-is
Function ReadFile(FilePath As String) As String
Dim filenum As Integer
If Dir(FilePath) > "" Then
filenum = FreeFile
Open FilePath For Input As filenum
ReadFile = Input(LOF(filenum), filenum)
Close filenum
Else
Debug.Print "File not found: " & FilePath
End If
End Function
' replaces all instances of a single word in the given document
Sub ReplaceAll(oldValue As String, newValue As String, doc As Document)
With doc.content.Find
.Forward = True
.Wrap = wdFindStop
.Execute findtext:=oldValue, replacewith:=newValue, Replace:=wdReplaceAll
End With
End Sub
Worker:工人:
Sub ReplaceAllVariables()
Dim variables As Variant, variable As Variant
Dim placeholder As String, realValue As String
variables = Split("date,disabledusers,and,any,other,variable,you,have", ",")
For Each variable In variables
placeholder = "%" & variable & "%"
realValue = ReadFile("\local folderpath\" & variable & ".txt")
realValue = TrimRight(realValue)
ReplaceAll placeholder, realValue, ActiveDocument
Next
End Sub
The TrimRight()
function only strips the final line break from the given input string. TrimRight()
函数仅从给定的输入字符串中TrimRight()
最后的换行符。 Any line breaks that are in the middle of the content are retained.保留在内容中间的任何换行符。 If this is a thing that can happen with your data, Word will create new paragraphs for every LF
it finds.如果您的数据可能会发生这种情况,Word 将为它找到的每个LF
创建新段落。 And it will draw boxes for every CR
it finds.它将为找到的每个CR
绘制框。
If you do have multi-line txt files, but don't want new paragraphs, and don't want boxes, either, modify the content of the text file before you use it (get rid of CRs, replace the LFs with vertical tabs, which are Word's way to represent "soft breaks", ie the same thing you get with Shift+Enter):如果您确实有多行 txt 文件,但不想要新的段落,也不想要框,请在使用之前修改文本文件的内容(去掉 CR,用垂直制表符替换 LF ,这是 Word 表示“软中断”的方式,即与 Shift+Enter 得到的结果相同):
realValue = ReadFile("\local folderpath\" & variable & ".txt")
realValue = TrimRight(realValue)
realValue = Replace(Replace(realValue, vbCr, ""), vbLf, vbVerticalTab)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.