尝试在保留旧名称的同时转换文件

时间:2016-06-01 12:03:53

标签: excel vba excel-vba

Hello Stackoverflow用户,

我正在尝试将文件从非Microsoft文件转换为excel

我使用以下代码进行了管理:

Sub FastaToExcel()
'
' Macro
'

'
fName = Application.GetOpenFilename()

Workbooks.OpenText Filename:=fName, Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
    , ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
    TrailingMinusNumbers:=True

    ActiveWorkbook.SaveAs Filename:="NewName.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWorkbook.Close SaveChanges:=True

End Sub

获取转换和重命名的文件。这很有效,并且推出了漂亮的NexName.xlsx。

但是,为了使命名动态,我根据这里的帖子(VBA Excel file to CSV, keeps CSV filename same as original workbook)尝试了以下代码:

Sub Macro1()
    NewName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
    ActiveWorkbook.SaveAs Filename:="C:\Users\Username\Desktop\" & NewName & ".csv", , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWorkbook.Close SaveChanges:=True
 End Sub

然而,这不适用于" ActiveWorkbook.Name"拉出包含宏的.xlsm文件的名称来转换文件,遗憾的是不使用我要保留名称的非Windows格式文件的名称,并将其用于新的.xlsx文件。

任何人都可以帮我解决这个问题吗?非常感谢。

[编辑]我也尝试使用@Jeeped建议的代码(由@skkakkar提出)在创建此主题的同一主题中,但这挂起在ActiveWorkbook.SaveAs行:

Sub FastaToExcel()
'
' Macro
'

'
fName = Application.GetOpenFilename()

Dim myPath As String, myFileName As String

myPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
If Not CBool(Len(Dir(myPath, vbDirectory))) Then MkDir Path:=myPath
myFileName = Left(ActiveWorkbook.Name, InStr(1, ActiveWorkbook.Name, ".xl", vbTextCompare) - 1) & ".fasta"

Debug.Print myPath & Chr(92) & myFileName

Workbooks.OpenText Filename:=fName, Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
    , ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
    TrailingMinusNumbers:=True

    ActiveWorkbook.SaveAs Filename:=myPath & Chr(92) & myFileName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWorkbook.Close SaveChanges:=True

End Sub

0 个答案:

没有答案