我需要引用什么?我该如何使用这个:
Dim fso As New FileSystemObject
Dim fld As Folder
Dim ts As TextStream
我收到一个错误,因为它无法识别这些对象。
我需要引用什么?我该如何使用这个:
Dim fso As New FileSystemObject
Dim fld As Folder
Dim ts As TextStream
我收到一个错误,因为它无法识别这些对象。
在Excel中,您需要设置对VBScript运行时库的引用。相关文件通常位于\Windows\System32\scrrun.dll
。
scrrun.dll
文件的完整名称和路径如果已启用访问VBA对象模型,则也可以直接在代码中执行此操作。
可以通过选中“文件”>“选项”>“信任中心”>“信任中心设置”>“宏设置”中的信任对VBA项目对象模型的访问
复选框来启用访问。
要添加引用:
Sub Add_Reference()
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference
End Sub
从stackoverflow获取而来,需要翻译的内容为:To remove a reference:
删除一个引用:Sub Remove_Reference()
Dim oReference As Object
Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")
Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference
End Sub
在Excel 2013中,对象创建字符串为:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
使用上面答案中的代码之外的替代代码:
Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")
这些人提供了如何使用文件系统对象的出色示例http://www.w3schools.com/asp/asp_ref_filesystem.asp
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>
按照上述步骤导入脚本运行时后,您需要进行一些微小的修改才能在Excel 2010(我的版本)中正常工作。下面的代码中,我还添加了用于让用户选择文件的代码。
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Dim fso As New Scripting.FileSystemObject