如何在VBA中使用FileSystemObject?


Answers:


178

在Excel中,您需要设置对VB脚本运行时库的引用。相关文件通常位于\Windows\System32\scrrun.dll

  • 要引用此文件,请加载Visual Basic编辑器(ALT+ F11
  • 从下拉菜单中选择工具>参考。
  • 将显示可用参考的列表框
  • 勾选“ Microsoft Scripting Runtime” 旁边的复选框
  • 文件的全名和路径scrrun.dll将显示在列表框下方
  • 点击OK按钮。

如果已启用对VBA对象模型的访问,则也可以直接在代码中完成此操作。

Access可以通过选中复选框启用Trust access to the VBA project object model在发现文件>选项>信任中心>信任中心设置>宏设置

VBA宏设置

要添加参考:

Sub Add_Reference()

    Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference

End Sub

删除参考:

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

您在Mac上做什么?
Thomas Fankhauser

是否没有办法通过命令行来执行此操作,例如包含库之类的东西?
LuizAngioletti 2015年

有没有一种方法可以自动勾选“ Microsoft Scripting Runtime”复选框?对于所有Excel文件?我正在使用Excel 2016
compski


13

在excel 2013中,对象创建字符串为:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

而不是上面答案中的代码:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

更明确地说,我通常将其视为Dim fso As Object
Marcucciboy2


2

添加参考之后,我不得不使用

Dim fso As New Scripting.FileSystemObject

2

如上所述导入脚本运行时后,您必须进行一些稍微的修改才能使其在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

希望对您有所帮助!

最好的祝福

法比奥

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.