【问题标题】:InStr function VBA: trouble comparing file name with text objectInStr 函数 VBA:将文件名与文本对象进行比较时出现问题
【发布时间】:2015-03-19 05:00:57
【问题描述】:

一般背景:

我正在尝试遍历 Word 文档中的文本行,其中每一行都是一个唯一的示例名称(例如 Sample1Sample2Sample3 em>),然后从特定文件夹中插入图像,该文件夹的文件名中包含样本名称(例如 Sample1 a.pngSample1 b.pngSample2 xyz.png, Sample3 xxx.png).

我正在使用的代码示例:

Dim fso As New FileSystemObject
Set MySource = fso.GetFolder("C:\Test\")
numParas = ActiveDocument.Paragraphs.Count

counter = 0
While counter < numParas
    counter = counter + 1
    sampleName = ActiveDocument.Paragraphs(counter).Range.Text
    For Each File In MySource.Files
        If InStr(File.Name, sampleName) > 0 Then 
            ' Insert script here to insert pictures
            MsgBox ("File found")
        End If
    Next File
Wend

疑问/问题:

  • 当我将 File.Name 与 sampleName(一个 Range.Text 对象)进行比较时,我无法让 InStr 工作。

  • 但是,如果我使用If InStr(File.Name, "Sample1") &gt; 0 Then 而不是If InStr(File.Name, sampleName) &gt; 0 Then,它确实有效;虽然这不允许我遍历许多示例名称。

从文件夹添加文件的其他选项:

此线程 (Loop through files in a folder using VBA?) 显示了循环浏览文件夹中文件的更快方法。我尝试使用 Dir 和以下代码:

Dim StrFile As String
Dim FolderStr As String

numParas = ActiveDocument.Paragraphs.Count
counter = 0
While counter < numParas
    counter = counter + 1
    sampleName = ActiveDocument.Paragraphs(counter).Range.Text
    FolderStr = "C:\Test\*" + sampleName + "*.png"
    MsgBox (FolderStr) 'First message box
    StrFile = Dir("C:\Test\*" + sampleName + "*.png")
    Do While Len(StrFile) > 0
        ' Insert script here to insert pictures
        MsgBox ("File found")
        StrFile = Dir
    Loop
Wend

疑问/问题:

  • 我无法以迭代方式创建 Dir 对象,因为我无法将 sampleName 文本对象与字符串连接起来。

例如,在上面脚本的第一个消息框中,我得到以下输出,文件地址位于两行而不是一个字符串。

C:\Test\*Sample1
*.png

感谢您提供的任何帮助!

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    当您使用inStr 比较两个项目File.NamesampleName 时,您忘记了Samplename 是包含paragraph ending mark 的段落中的文本。您需要以任何方式剪切最后一个字符,例如:

    sampleName = ActiveDocument.Paragraphs(counter).Range.Text
    sampleName = Left(sampleName, Len(sampleName) - 1)   'this new line removes paragraph ending mark
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多