使用基于单元格值的名称和文件位置另存为txt

时间:2018-03-23 12:32:44

标签: vba excel-vba excel

我需要将某些纸张导出为txt,我无法做到。我以这种方式尝试但不要去正确的文件位置:

Dim filePath As String 
Dim fileName As String 

filePath = Sheet1.Range("B3").Value

fileName = Sheet22.Range("N3").Value

    Sheet14.Select
    ActiveWorkbook.SaveAs fileName:= _
          fileName, 
FileFormat:= _
        xlText, CreateBackup:=False

这是正确的吗?

1 个答案:

答案 0 :(得分:0)

除非您想要保存当前的工作表,否则您应该尝试这样做:

Dim ws As Excel.Worksheet
Dim fileName As String

Sub Export_WS()

Set ws = Worksheets("Exportsheet")

'Get file path your way by this Sub
GetFile

'Copy the ws to a new workbook
ws.Copy

'With the new wb:
With Workbooks(Workbooks.Count)
'Save and close the new workbook
    .SaveAs fileName:=fileName, FileFormat:=xlTextPrinter
    .Close False
End With

End Sub

以下是我获取文件链接的方式

Function GetFile() As String

Dim filename_path As Variant
filename_path = Application.GetOpenFilename(FileFilter:="xyz* (*.txt), *.txt", Title:="Select file")
If filename_path = False Then Exit Function
GetFile = filename_path
fileName = filename_path

End Function

希望有所帮助。

或者像你建议的Cell Value

fileName = SheetXYZ.Range("A1").Value

当然您也可以手动分配文件名:

fileName = "c:filename.txt"

其他信息在这里: File Operations