我正在导入.txt
文件并重新格式化数据以删除逗号。当我尝试保存它时,它会给我运行时错误。我怎样才能解决这个问题?非常感谢任何帮助!
Sub SaveNewFile()
ActiveCell.SpecialCells(xlLastCell).Select
endrow = Selection.Row
Cells(1, 1).Select
If TopSide = 1 Then
BoardName = BoardName & "_TOP"
Else
BoardName = BoardName & "_BOT"
End If
filesavename = Application.GetSaveAsFilename( _
InitialFilename:=BoardName, FileFilter:="YTV CAD Files (*.ycd), *.ycd")
If filesavename = "False" Then End
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile(filesavename, True)
For i = 1 To 17
For j = 1 To 2
a.write (Cells(i, j) & " ")
Next j
a.writeline
Next i
For i = 18 To endrow
For j = 1 To 7
a.write (Cells(i, j) & " ")
Next j
a.writeline
Next i
a.Close
Application.DisplayAlerts = False
'ActiveWorkbook.SaveAs Filename:= _
' filesavename, _
' FileFormat:=xlTextPrinter, CreateBackup:=False
jmessage = MsgBox(filesavename & " has been generated successfully!", vbOKOnly, "YCD Export")
Call YCDFileLocationIni
'Application.DisplayAlerts = True
Workbooks.Open (CADFileName)
Workbooks(ShortCADFileName).Activate
ActiveWorkbook.Close
End Sub
答案 0 :(得分:1)
首先要做的事情
更改
filesavename = Application.GetSaveAsFilename( _
InitialFileName:=BoardName, _
FileFilter:="YTV CAD Files (*.ycd), *.ycd")
If filesavename = "False" Then End
到
Dim filesavename As Variant
filesavename = Application.GetSaveAsFilename( _
InitialFileName:=BoardName, _
FileFilter:="YTV CAD Files (*.ycd), *.ycd")
If filesavename = False Then Exit Sub
你永远不应该使用End
。理由很简单。这就像使用POWER OFF按钮关闭计算机一样。 End语句突然停止代码执行,而不调用Unload,QueryUnload或Terminate事件或任何其他Visual Basic代码。其他程序保留的对象引用(如果有)也是无效的。
接下来,请避免使用.Select/.Activate
INTERESTING READ
其他没有意义的事情(但除非你有Option Explicit On,否则不会产生错误)是BoardName
。你在哪里设定它以前的价值?与TopSide
相同。使用Option Explicit
,问题的主要部分将消失。
这绝对没有任何意义
Workbooks.Open (CADFileName)
Workbooks(ShortCADFileName).Activate
CADFileName
或ShortCADFileName
您是否也逐步完成了YCDFileLocationIni
的代码?
总而言之,一旦我对您的代码进行了上述更改以及声明CADFileName
,ShortCADFileName
之类的一些小改动,您的代码就会毫无错误地运行。