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.
asked Jul 13, 2010 at 0:00
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
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
answered Jul 13, 2010 at 10:46
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
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
16.5k5 gold badges54 silver badges111 bronze badges
answered Jul 13, 2010 at 0:04
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
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
answered May 4, 2018 at 16:18
DO_oK 11 / 11 / 7 Регистрация: 05.11.2011 Сообщений: 87 |
||||
1 |
||||
08.08.2017, 09:32. Показов 8436. Ответов 11 Метки нет (Все метки)
Привет! Поискал решение, не нашел, давно не обращался за помощью на форум так вот ругается на первую же строчку кода, т.е. на «Sub FSD()». Весь код:
0 |
es geht mir gut 11266 / 4748 / 1183 Регистрация: 27.07.2011 Сообщений: 11,438 |
|
08.08.2017, 09:42 |
2 |
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 |
Если речь идет об этом то видимо нет. Можно поподробней? Миниатюры
0 |
6880 / 2811 / 535 Регистрация: 19.10.2012 Сообщений: 8,576 |
|
08.08.2017, 10:17 |
6 |
Сообщение было отмечено DO_oK как решение РешениеНайдите и подключите Microsoft scripting runtime scrrun.dll
3 |
mobile 26784 / 14463 / 3192 Регистрация: 28.04.2012 Сообщений: 15,782 |
||||
08.08.2017, 10:24 |
7 |
|||
Библиотека Microsoft Scripting Runtime. Но часто применяют позднее связывание без объявления в референсах: вместо Dim fso As New 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 |
Аппаздал Зато в этом случае ничего не надо подключать .
0 |
DO_oK 11 / 11 / 7 Регистрация: 05.11.2011 Сообщений: 87 |
||||
09.08.2017, 07:37 [ТС] |
10 |
|||
Попробовал так, остается ошибка, не подскажите в чем дело?
0 |
6880 / 2811 / 535 Регистрация: 19.10.2012 Сообщений: 8,576 |
|
09.08.2017, 08:45 |
11 |
Ошибка в TextStream — что это, куда это… никто не знает.
0 |
shanemac51 Модератор 11400 / 4710 / 759 Регистрация: 07.08.2010 Сообщений: 13,664 Записей в блоге: 4 |
||||
09.08.2017, 09:21 |
12 |
|||
у меня заработало, но после исправлений
0 |
copper-top Пользователь Сообщений: 1051 |
#1 19.12.2017 21:43:09 здравствуйте. прошу помочь. скопировал два макроса в файл. макрос Content_for_etfs_convert отработал без проблем. после запускаю replaceTxts. выходит ошибка и выделяется fso As New FileSystemObject синим. в файле, с которого скопировал, работает как надо.может, какие то библиотеки надо подключить?
|
||
Hugo Пользователь Сообщений: 23378 |
#2 19.12.2017 21:48:58
— не может, а обязательно. Microsoft Scripting Runtime. Изменено: Hugo — 19.12.2017 21:50:03 |
||
The_Prist Пользователь Сообщений: 14270 Профессиональная разработка приложений для MS Office |
#3 19.12.2017 21:51:15 Либо для файла с кодом в VBA -Tools -References подключите библиотеку Microsoft Scripting Runtime, либо запишите процедуру так:
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Hugo, The_Prist, подключил библиотеку Microsoft Scripting Runtime. заработало.спасибо. |
|
БМВ Модератор Сообщений: 21679 Excel 2013, 2016 |
copper-top, ну реально кажется, что вы даже не пытаетесь решить проблему самостоятельно, сразу сюда. Да и в целом вопрос к excel ваще не относится. Чистой воды VBS скрипты. То что они работают в VBA, то это только до первой Wscript. … (Я часто Excel как отладчик пользую, для простых и не очень VBS) . По вопросам из тем форума, личку не читаю. |
copper-top Пользователь Сообщений: 1051 |
#6 19.12.2017 22:23:58
как я решу, если макросами умею только пользоваться. макросы получил на этом форуме, за что спасибо и форуму и авторам.
так и есть. получил как скрипт. был скриптом — стал макросом. |
||||
БМВ Модератор Сообщений: 21679 Excel 2013, 2016 |
#7 19.12.2017 22:37:05 Offtop
Как скриптом был, так им и остался, Возможно кто-то кроме меня из форумчан застал первые выпуски 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.