Vba 将变量从TXT文件导入Word文档

Vba 将变量从TXT文件导入Word文档,vba,ms-word,Vba,Ms Word,长话短说,谢谢阅读:) 我正在尝试自动分析广告输出。我向客户发送PowerShell脚本以将广告数据导出到CSV。他们向我发送CSV文件,我将这些文件导入一个名为Wegalviance ACL(简称ACL)的分析工具。在ACL中,我能够过滤/匹配/比较以及我需要做的任何事情 到目前为止一切都很好。现在我想使用这些结果并将它们放入.docx文件中,麻烦来了。ACL无法导出到docx,只能导出xlsx/txt/csv/html/json/del 好吧,我们可以解决这个问题(或者我是这么想的),我制作

长话短说,谢谢阅读:)

我正在尝试自动分析广告输出。我向客户发送PowerShell脚本以将广告数据导出到CSV。他们向我发送CSV文件,我将这些文件导入一个名为Wegalviance ACL(简称ACL)的分析工具。在ACL中,我能够过滤/匹配/比较以及我需要做的任何事情

到目前为止一切都很好。现在我想使用这些结果并将它们放入.docx文件中,麻烦来了。ACL无法导出到docx,只能导出xlsx/txt/csv/html/json/del

好吧,我们可以解决这个问题(或者我是这么想的),我制作了一个
模板.docx
template.docx
中,我编写了类似
%certainvariable%
的占位符

在ACL中,我创建了一个命令,将我需要的所有变量写入名为
%variablename%.txt的文件中,在txt中是我需要的值

例如:

ACL创建
disabledusers.txt
。如果你打开txt,它只显示10个,这意味着我们有10个被禁用的用户

然后我尝试创建一个VBA宏来导入txt文件,并使用包含的值替换Word文档中相应的
%…%
文本

这一切看起来都很顺利,直到我注意到在运行脚本之后,我得到了
20
,后面是一个表示“我不知道如何显示这个字符”的框

在运行脚本之前:

运行脚本后:

我导入的.txt内容的图片:

最后但并非最不重要的是我从word宏管理器中使用的VBS代码(为了方便起见,我只上传了1个导入和替换作业,但在我的脚本中,我只为每个文件和变量复制了30次):

当我手动打开
date.txt
并删除第二行时,一切似乎都正常。但我想让它自动化

我试过了

  • 使用
    \n\r
    \r
    添加
    拆分文本文件、/n
    拆分新日期,/n
    均无效
  • 使用sed命令删除第二行。没用
  • 找到了许多findstr方法来删除所谓的回车(crlf) 但要么我的txt文件突然空了,要么我的Word文件中还有框
我愿意接受关于任何编程语言的建议,(我对它们都很糟糕)我会按照正确的顺序排列所有东西,使其正常工作;)

提前谢谢大家! 当然,如果你需要更多的信息,可以直接问

由于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

问题似乎在于新线(CRLF)。你必须摆脱它

当我们在做这件事的时候,让我们也去掉“我已经复制了那个代码30次”的部分,这是解决这个问题的一个可怕的方法。循环更好

助手:

' 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("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
TrimRight()
函数仅从给定输入字符串中去除最后一个换行符。保留在内容中间的任何断线。如果您的数据可能出现这种情况,Word将为找到的每个
LF
创建新段落。它将为找到的每个
CR
绘制框

如果您确实有多行txt文件,但不想要新段落,也不想要方框,请在使用文本文件之前修改文本文件的内容(去掉CRs,用垂直制表符替换LFs,这是Word表示“软中断”的方式,即与Shift+Enter的方式相同):


从VisualBasic的第一个版本的帮助中,文件已经使用Open语句和其他相关语句和函数(如下所列)进行了处理。这些机制最终将被逐步淘汰,取而代之的是FSO对象模型,但它们在Visual Basic 6.0..PS中得到了充分支持,该注释已有25年历史。除了此弃用警告之外,
Open
将在txt文件采用意外编码(例如UTF-8)时弄乱数据。你会看到当文本带有重音字符时,你的情况是否正常。FWIW,如果你将.txt文件的扩展名改为.doc,Word会将其作为Word文档打开。谢谢你的回答tomalak,我完全同意你的观点,粘贴导入30次是丑陋和效率低下的,但由于缺乏编码经验,这是我能想到的最好的方法;)目前我没有代码,也没有文件,明天会用它进行测试。我是否正确地认为我需要更改包含所有variable.txt文件的文件夹的文件路径?然后将所有变量名添加到split命令。还有什么需要补充或更改的吗?感谢您今天花了大部分时间让这部分正常工作,但仍然失败了——修改路径,添加变量名。但在使用之前,请确保您了解所有这些是如何工作的。它有助于在VBA IDE(F9)中设置断点,并在查看变量值(查看->局部变量窗口)的同时逐步执行代码行(F8)。tomalak,我现在正在尝试您的代码,它将从word文档中删除所有%variable%,但不会用任何其他内容替换它们。我在末尾添加了一个MsgBox(变量),它确实会给我弹出所有变量名“date,disabledusers等”。我还注意到,当我打开view>locals窗口时,我看不到变量的任何值。使用
Debug.Print
而不是
MsgBox
,这就不那么烦人了(打开即时窗口以查看调试.打印的输出。
)。在编写代码时,我看不出代码有任何错误,您确定没有对其进行任何更改吗?已修复!必须替换\local folderpath而不是filepath;P
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
realValue = ReadFile("\local folderpath\" & variable & ".txt")
realValue = TrimRight(realValue)
realValue = Replace(Replace(realValue, vbCr, ""), vbLf, vbVerticalTab)