以下Excelmacros的VBA代码有什么问题?

以下代码是Excelmacros的VBA代码。 目标是从文件Impeller_hub.dat读取input并将其写入copy_hub.dat 。 我收到的错误消息说,有一个types不匹配,运行时错误'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 

像这样的东西适合我(尽可能多地使用你的代码):

 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)来创build它,并删除行Set stream = fso.OpenTextFile(stream2,8)

如果你想从文件Impeller_hub.dat读取数据并写入文件copy_hub.dat ,那么你需要两个TextStreamvariables和两个单独的fso.OpenTextFile调用:一个使用第二个参数ForReading ,另一个使用第二个参数ForWriting

或者,如果要将数据添加到文件Impeller_hub.dat的末尾,则 – 因为CLR已经写入fso.OpenTextFile的第二个参数应该是ForAppending