我的目标是将 excel 文件导出为 txt 文件格式。这个想法是有一个 GUI 让用户选择她/他希望导出的 excel 文件,她/他可以决定保存哪个文件路径和文件名。用户完成输入输出设置后,只需点击导出文本按钮,即可将excel文件导出为txt文件并保存在自己指定的位置。图形用户界面如下
我有一个将excel文件转换为txt格式的宏
Private Sub ConvertToText()
ActiveWorkbook.SaveAs FileName:="C:\Projects\ExelToText\Text.txt", FileFormat:=xlCurrentPlatformText, CreateBackup:=False
End Sub
我的问题是如何将 FileInput 和 FileOutput 中的值作为变量传递给上面的宏,而不是对文件路径进行硬编码。感谢您的帮助,如果您有更好的建议,请分享出来。谢谢
下面是完整的源代码
Private Sub ReadButton_Click()
OpenWorkbookUsingFileDialog
End Sub
------------------------------
Private Sub WriteButton_Click()
WriteWorkbookUsingFileDialog
End Sub
------------------------------
Private Sub ExportButton_Click()
ConvertToText
End Sub
------------------------------
Private Sub OpenWorkbookUsingFileDialog()
Dim fdl As FileDialog
Dim FileName As String
Dim FileChosen As Integer
Set fdl = Application.FileDialog(msoFileDialogFilePicker)
fdl.Title = "Please Select a Excel File"
fdl.InitialFileName = "c:\"
fdl.InitialView = msoFileDialogViewSmallIcons
fdl.Filters.Clear
fdl.Filters.Add "Excel Files", "*.xlsx; *.xls"
FileChosen = fdl.Show
If FileChosen <> -1 Then
MsgBox "You have choosen nothing"
ReadTextBox = Null
Else
MsgBox fdl.SelectedItems(1)
FileName = fdl.SelectedItems(1)
ReadTextBox = FileName
End If
End Sub
-----------------------------------
Private Sub WriteWorkbookUsingFileDialog()
Dim file_name As Variant
file_name = Application.GetSaveAsFilename( _
FileFilter:="Text Files,*.txt,All Files,*.*", _
Title:="Save As File Name")
If file_name = False Then Exit Sub
If LCase$(Right$(file_name, 4)) <> ".txt" Then
file_name = file_name & ".txt"
End If
WriteTextBox = file_name
End Sub
----------------------------
Private Sub ConvertToText()
ActiveWorkbook.SaveAs FileName:="C:\Projects\ExelToText\Text.txt",FileFormat:=xlCurrentPlatformText, CreateBackup:=False
End Sub