以下代码是Excel宏的VBA代码。目标是从文件Impeller_hub.dat
读取输入并将其写入copy_hub.dat
。我收到的错误消息表明存在类型不匹配,运行时错误“13”。错误在哪里以及如何纠正?
Private Sub fn_write_to_text_Click()
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim stream As TextStream
Dim stream2 As String
LastCol = ActiveSheet.UsedRange.Columns.Count
LastRow = ActiveSheet.UsedRange.Rows.Count
stream2 = "C:\Users\devanandd\Desktop\copy_hub.dat"
Set stream = fso.OpenTextFile("C:\Users\devanandd\Desktop\Files\NUMECA\Impeller_Hub.dat", stream2, True)
CellData = ""
For i = 1 To LastRow
For j = 1 To LastCol
CellData = Trim(ActiveCell(i, j).Value)
stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData
Next j
Next i
stream.Close
MsgBox ("Job Done")
End Sub
答案 0 :(得分:0)
这样的东西对我有用(尽可能多地使用你的代码):
Option Explicit
Option Private Module
Private Sub fn_write_to_text_Click()
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
Dim fso As Object
Dim stream As Object
Dim stream2 As String
Dim i As Long
Dim j As Long
Set fso = CreateObject("Scripting.FileSystemObject")
LastCol = ActiveSheet.UsedRange.Columns.Count
LastRow = ActiveSheet.UsedRange.Rows.Count
stream2 = "C:\YOURPATH\Desktop\aaa.txt"
'Uncomment the next line if you do not have the file
'Set stream = fso.CreateTextFile(stream2, True)
Set stream = fso.OpenTextFile(stream2, 8) '8 is ForAppending
CellData = ""
For i = 1 To LastRow
For j = 1 To LastCol
CellData = Trim(ActiveCell(i, j).value)
stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData
Next j
Next i
stream.Close
MsgBox ("Job Done")
End Sub
如果桌面上有aaa.txt
文件,则以下代码可以使用。如果你还没有写:
Set stream = fso.CreateTextFile(stream2, True)
创建并删除第Set stream = fso.OpenTextFile(stream2,8)
行。
答案 1 :(得分:0)
如果您要阅读文件Impeller_hub.dat
并写入文件copy_hub.dat
,那么您需要两个TextStream
个变量,以及两个单独的fso.OpenTextFile
调用:一个第二个参数ForReading
,另一个参数为ForWriting
。
或者,如果要将数据添加到文件末尾Impeller_hub.dat
,那么 - 正如CLR已经写的那样 - fso.OpenTextFile
的第二个参数应为ForAppending
。