2017-06-19 218 views
1

我在VBA中并不是很坚定,我一直在尝试在Word中使用我之前在Excel中编写的函数。 (如果这是工作完美!)VBA Word 2013:Scripting.FileSystemObject:运行时错误424 - 对象需要

的功能经过一个文本文件,并有一定的(寻求)其他字符串之后返回一个字符串:

Function keySearch(ByVal sSearch As String) As String 
Dim fso As New FileSystemObject 
Dim FileNum 
Dim DataLine As String 
Dim posOf_A As Integer 
Dim filepath As String 

keySearch = "" 

'Create filesystem object 
Set fso = CreateObject("Scripting.FileSystemObject") 

'filepath to textfile 
filepath = ActiveWorkbook.Path & "\temp.txt" 

Set FileNum = fso.OpenTextFile(filepath, 1) '<--- This is where the error occurs! 

Do While Not FileNum.AtEndOfStream 
    DataLine = FileNum.ReadLine 
    posOf_A = InStr(1, DataLine, sSearch, vbTextCompare) 
    If posOf_A = 1 Then 
     keySearch = Right(DataLine, Len(DataLine) - Len(sSearch)) 
    End If 
Loop 

FileNum.Close 

End Function 

在文本文件是线路发生错误应该打开。 错误消息:运行时错误424:需要对象。

我已经分裂排队尽可能缩小从代码通过Excel下工作完美无缺功能这个原线搜索:

FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile(ActiveWorkbook.Path & "\temp.txt", 1) 

但我似乎就是不被能够使它工作..我已经看到了多个互联网上的例子(看起来)完全一样,我正在做它...

PS:Microsoft脚本运行时激活。

预先感谢任何真正赞赏的帮助!

回答

1

变化ActiveWorkbook.Path变为ActiveDocument.Path。您正在尝试引用文件路径的活动Excel工作簿。

+0

就是这样!非常感谢! – budekatude

+0

没问题。不客气! – Quint

相关问题