Dim fso as new filesystemobject ошибка

21K

18 февраля 2007 года

dedmakar

6 / / 25.12.2006

Хочу создать фаил. Набираю этот КОД:
Private Sub Command1_Click()
Dim fso As New FileSystemObject
fso.CreateTextFile «C:file1.txt»
End Sub
Выдаёт ошибку:
«User-defined type not defined.»
А в коде выделяет:
Private Sub Command1_Click()
Dim fso As New FileSystemObject
fso.CreateTextFile «C:file1.txt»
End Sub
Что делать? Я только новичок, если что SORRY….

2 ответа

405

19 февраля 2007 года

Dmitrii

554 / / 16.12.2004

Вам нужно либо подключить к проекту библиотеку Microsoft Scripting Runtime (файл scrrun.dll), либо использовать «позднее связывание». Пример для последнего способа:

Код:

Dim fso As Object, myFile As Object
Set fso = CreateObject(«Scripting.FileSystemObject»)
Set myFile = fso.CreateTextFile(«c:file1.txt»)
myFile.WriteLine(«This is a test.»)
myFile.Close

21K

20 февраля 2007 года

dedmakar

6 / / 25.12.2006

Спасибо!!! Я воспользовался Microsoft Common Dialog Control 6.0..
Полное объяснение тут

Is there something that I need to reference? How do I use this:

Dim fso As New FileSystemObject
Dim fld As Folder
Dim ts As TextStream

I am getting an error because it does not recognize these objects.

Andrei Konstantinov's user avatar

asked Jul 13, 2010 at 0:00

Alex Gordon's user avatar

Within Excel you need to set a reference to the VBScript run-time library.
The relevant file is usually located at WindowsSystem32scrrun.dll

  • To reference this file, load the
    Visual Basic Editor (ALT+F11)
  • Select Tools > References from the drop-down menu
  • A listbox of available references will be displayed
  • Tick the check-box next to ‘Microsoft Scripting Runtime
  • The full name and path of the scrrun.dll file will be displayed below the listbox
  • Click on the OK button.

This can also be done directly in the code if access to the VBA object model has been enabled.

Access can be enabled by ticking the check-box Trust access to the VBA project object model found at File > Options > Trust Center > Trust Center Settings > Macro Settings

VBA Macro settings

To add a reference:

Sub Add_Reference()

    Application.VBE.ActiveVBProject.References.AddFromFile "C:WindowsSystem32scrrun.dll"
'Add a reference

End Sub

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

Stephen Ostermiller on Strike's user avatar

answered Jul 13, 2010 at 10:46

Robert Mearns's user avatar

Robert MearnsRobert Mearns

11.8k3 gold badges38 silver badges42 bronze badges

3

In excel 2013 the object creation string is:

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

instead of the code in the answer above:

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

answered Jul 31, 2016 at 19:54

Stefano Spinucci's user avatar

1

These guys have excellent examples of how to use the filesystem object 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
%> 

shA.t's user avatar

shA.t

16.5k5 gold badges54 silver badges111 bronze badges

answered Jul 13, 2010 at 0:04

Gerald Ferreira's user avatar

Gerald FerreiraGerald Ferreira

1,3492 gold badges22 silver badges44 bronze badges

1

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

answered Feb 15, 2018 at 23:25

thedanotto's user avatar

thedanottothedanotto

6,8335 gold badges45 silver badges43 bronze badges

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I’ve also add the code used to the user to pick a file.

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

Stephen Ostermiller on Strike's user avatar

answered May 4, 2018 at 16:18

FIRE FOX's user avatar

DO_oK

11 / 11 / 7

Регистрация: 05.11.2011

Сообщений: 87

1

08.08.2017, 09:32. Показов 8436. Ответов 11

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Привет! Поискал решение, не нашел, давно не обращался за помощью на форум так вот ругается на первую же строчку кода, т.е. на «Sub FSD()». Весь код:

PureBasic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Sub FSD()
    FolderName = "O:путькпапке_кириллицей" 
 
    Dim coll As New Collection, filename
    filename = Dir(FolderPath$ & "*.htm")
    While filename <> ""
        coll.Add filename    ' ñ÷èòûâàåì â êîëåêöèþ coll íóæíûå èìåíà ôàéëîâ
        filename = Dir
    Wend
    Dim pos As Long
    Dim rowcunt As Long
    rowcunt = 3
    pcname = "<TR><TD><TD><TD>Êîìïüþòåð&nbsp;&nbsp;<TD>"
    
    For Each filename In coll
     Dim fso As New FileSystemObject
     Dim ts As TextStream
     Set ts = fso.OpenTextFile(FolderName & filename, ForReading)
     Dim TextLine As String
     Do Until ts.AtEndOfStream
         TL = ts.ReadLine
         pos = InStr(1, pcname, TL)
         If pos > 0 Then
            Range("B" & rowcunt).Value = Right(TL, Len(TL) - 42)
         End If
     Loop
     rowcunt = rowcunt + 1
     ts.Close
    Next
End Sub



0



es geht mir gut

11266 / 4748 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

08.08.2017, 09:42

2

Цитата
Сообщение от DO_oK
Посмотреть сообщение

FSD()

Обзови по другому FSD_1 , например.



0



11 / 11 / 7

Регистрация: 05.11.2011

Сообщений: 87

08.08.2017, 09:45

 [ТС]

3

Переименовал в FSD_1(), не работает. Вообще от имени не зависит пробовал разные варианты и кириллицу тоже



0



6880 / 2811 / 535

Регистрация: 19.10.2012

Сообщений: 8,576

08.08.2017, 09:46

4

Библиотека с FileSystemObject подключена?



0



11 / 11 / 7

Регистрация: 05.11.2011

Сообщений: 87

08.08.2017, 09:50

 [ТС]

5

Если речь идет об этом то видимо нет. Можно поподробней?

Миниатюры

User-defined type not defined. Ругается на объявление корневой процедуры
 



0



6880 / 2811 / 535

Регистрация: 19.10.2012

Сообщений: 8,576

08.08.2017, 10:17

6

Лучший ответ Сообщение было отмечено DO_oK как решение

Решение

Найдите и подключите Microsoft scripting runtime scrrun.dll



3



mobile

Эксперт MS Access

26784 / 14463 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

08.08.2017, 10:24

7

Библиотека Microsoft Scripting Runtime. Но часто применяют позднее связывание без объявления в референсах: вместо Dim fso As New FileSystemObject пишут

Visual Basic
1
2
Dim fso As Object
Set fso = createobject("scripting.FileSystemObject")

Добавлено через 31 секунду
Аппаздал



4



11 / 11 / 7

Регистрация: 05.11.2011

Сообщений: 87

08.08.2017, 10:25

 [ТС]

8

Проблема решилась, спасибо!

Найдите и подключите Microsoft scripting runtime scrrun.dll



0



es geht mir gut

11266 / 4748 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

08.08.2017, 10:29

9

Цитата
Сообщение от mobile
Посмотреть сообщение

Аппаздал

Зато в этом случае ничего не надо подключать .



0



DO_oK

11 / 11 / 7

Регистрация: 05.11.2011

Сообщений: 87

09.08.2017, 07:37

 [ТС]

10

Попробовал так, остается ошибка, не подскажите в чем дело?

PureBasic
1
2
3
4
5
6
7
8
     Dim fso As Object
     Set fso = CreateObject("scripting.FileSystemObject")
     Dim ts As TextStream
     Set ts = fso.OpenTextFile(FolderName & filename, ForReading)
     Dim TextLine As String
     Do Until ts.AtEndOfStream
         TL = ts.ReadLine
..........



0



6880 / 2811 / 535

Регистрация: 19.10.2012

Сообщений: 8,576

09.08.2017, 08:45

11

Ошибка в TextStream — что это, куда это… никто не знает.
Замените на Object



0



shanemac51

Модератор

Эксперт MS Access

11400 / 4710 / 759

Регистрация: 07.08.2010

Сообщений: 13,664

Записей в блоге: 4

09.08.2017, 09:21

12

у меня заработало, но после исправлений

Visual Basic
1
2
3
4
5
6
foldername = "O:путькпапке_кириллицей"
'''
pos = InStr(1, tl, pcname)
If pos > 0 And Len(tl) > 42 Then
Range("B" & rowcunt).Value = Right(tl, Len(tl) - 42)
End If



0



 

copper-top

Пользователь

Сообщений: 1051
Регистрация: 22.10.2016

#1

19.12.2017 21:43:09

здравствуйте. прошу помочь. скопировал два макроса в файл. макрос Content_for_etfs_convert отработал без проблем. после запускаю replaceTxts. выходит ошибка и выделяется fso As New FileSystemObject синим. в файле, с которого скопировал, работает как надо.может, какие то библиотеки надо подключить?

Код
Sub Content_for_etfs_convert()
Kill "D:option programsотборIN*.*"
Kill "D:option programsотборOUT*.*"
  Dim fso
  Set fso = CreateObject("scripting.filesystemobject"):  fso.CopyFolder "C:UsersАдминистраторDownloadsStocksrcdistdownloads", "D:option programsотборIN"
 
Set fso = CreateObject("Scripting.FileSystemObject")
cPath = fso.GetParentFolderName(ThisWorkbook.FullName)
 
cPathIn = cPath & "In"
cPathOut = cPath & "Out"
 
Set Folder = fso.GetFolder(cPathIn)
For Each File In Folder.Files
   If fso.GetExtensionName(File.Name) = "txt" Then
      With fso.OpenTextFile(cPathIn & File.Name, 1, True)
         cIn = .ReadAll
         .Close
      End With
      cOut = vbCrLf & "DATE"
      arrL = Split(cIn, vbLf)
      For i = LBound(arrL) To UBound(arrL)
         If Len(arrL(i)) > 0 Then
            arrD = Split(arrL(i), ",")
            arrD(0) = Right(arrD(0), 2) & "." & Mid(arrD(0), 5, 2) & "." & Left(arrD(0), 4)
            For j = 1 To 4
               cnum = Replace(arrD(j), ".", ",")
               arrD(j) = Replace(CStr(Round(CDbl(cnum), 2)), ",", ".")
            Next
            cnum = Replace(arrD(6), ".", ",")
            arrD(6) = Replace(CStr(Round(CDbl(cnum), 0)), ",", ".")
            cOut = cOut & vbCrLf & Join(Array(arrD(0), arrD(1), arrD(2), arrD(3), arrD(4), arrD(6)), vbTab)
         End If
      Next
      With fso.OpenTextFile(cPathOut & File.Name, 2, True)
         .Write cOut
         .Close
      End With
   End If
Next

 
MsgBox "Ok"

End Sub
Sub replaceTxts()
    Dim fso As New FileSystemObject, curFolder As Folder, curFile As File
    folderPath = "D:option programsотборOUT"
    Set curFolder = fso.GetFolder(folderPath)
    For Each curFile In curFolder.Files
        If Right(curFile.Path, 4) = ".txt" Then
            curFile.copy Replace(curFile.Path, ".txt", ".csv")
            curFile.Delete
        End If
    Next curFile
End Sub
 

Hugo

Пользователь

Сообщений: 23378
Регистрация: 22.12.2012

#2

19.12.2017 21:48:58

Цитата
copper-top написал:
может, какие то библиотеки надо подключить?

— не может, а обязательно. Microsoft Scripting Runtime.
Или не подключайте, а юзайте как в первом коде, через createobject

Изменено: Hugo19.12.2017 21:50:03

 

The_Prist

Пользователь

Сообщений: 14270
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#3

19.12.2017 21:51:15

Либо для файла с кодом в VBA -Tools -References подключите библиотеку Microsoft Scripting Runtime, либо запишите процедуру так:

Код
Sub replaceTxts()
    Dim fso As Object, curFolder As Folder, curFile As File
    Set fso = CreateObject("scripting.filesystemobject")
    folderPath = "D:option programsотборOUT"
    Set curFolder = fso.GetFolder(folderPath)
    For Each curFile In curFolder.Files
        If Right(curFile.Path, 4) = ".txt" Then
            curFile.copy Replace(curFile.Path, ".txt", ".csv")
            curFile.Delete
        End If
    Next curFile
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Hugo, The_Prist,  подключил библиотеку Microsoft Scripting Runtime. заработало.спасибо.

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

copper-top,  ну реально кажется, что вы даже не пытаетесь решить проблему самостоятельно, сразу сюда.
Dim fso As New FileSystemObject — это зачем?  ограничте это Dim fso As Object,   Folder,  File — в туже топку

Да и в целом  вопрос к excel ваще не относится. Чистой воды VBS скрипты. То что они работают в VBA, то это только до первой Wscript. … (Я часто Excel как отладчик пользую, для  простых и не очень VBS) .

По вопросам из тем форума, личку не читаю.

 

copper-top

Пользователь

Сообщений: 1051
Регистрация: 22.10.2016

#6

19.12.2017 22:23:58

Цитата
БМВ написал:
не пытаетесь решить проблему самостоятельно

как я решу, если макросами умею только пользоваться. макросы получил на этом форуме, за что спасибо и форуму и авторам.

Цитата
БМВ написал:
Чистой воды VBS скрипты

так и есть. получил как скрипт. был скриптом — стал макросом.  

 

БМВ

Модератор

Сообщений: 21679
Регистрация: 28.12.2016

Excel 2013, 2016

#7

19.12.2017 22:37:05

Offtop

Цитата
copper-top написал: был скриптом — стал макросом

Как скриптом был, так им и остался, Возможно кто-то кроме меня из форумчан застал первые выпуски Excel в которых реально макросы записывались в лист условными командами вот так например NDX = 1: Do While NDX < IDN: SendKeys «{down}»: NDX = NDX + 1: Loop , вот с тех пор и повелось, что все что на VBA макросом кличут, хотя это уже давно не так.

По вопросам из тем форума, личку не читаю.

  • Remove From My Forums
  • Question

  • I have encountered an error when trying to create a FileSystemObject.  This code has been running fine for about a year and a half, but now on one system my user is recieving:


           «Run-Time error ‘429’

           ActiveX component can’t create object»


     The error occurs on this line:

              Dim fso as Object

               fso = CreateObject(«Scripting.FileSystemObject»)

Answers

  •          Dim fso as Scripting.FileSystemObject

              set fso = new Scripting.FileSystemObject

    Also reference the MS Scritping Runtime. That’s all I can do.

  • Digitronic maxi 2 ошибки
  • Digital pump switch ошибка ef
  • Digi sm 300 ошибка ацп
  • Digi sm 100 ошибка e71 печать запрещена
  • Different levels of indirection ошибка