通过excel vba GUI将excel文件导出为txt格式

时间:2013-10-31 13:29:34

标签: excel vba excel-vba

我的目标是将excel文件导出为txt文件格式。想法是有一个GUI,让用户选择她/他希望导出的excel文件,并且他/她可以决定保存哪个文件路径和文件名。一旦用户完成输入和输出设置,他/她只需要单击导出文本按钮将excel文件导出到txt文件并保存在他/她已决定的位置。 GUI如下

enter image description here

我有一个宏来将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

1 个答案:

答案 0 :(得分:1)

这样你的子程序ConvertToText需要一个文件路径/字符串参数:

Private Sub ConvertToText(sourcePath as String, destPath as String)
    Dim wb as Workbook
    Set wb = Workbooks.Open(sourcePath)
    wb.SaveAs FileName:=destPath,       
    FileFormat:=xlCurrentPlatformText, CreateBackup:=False
    wb.Close
End Sub

然后,对ExportButton进行少量修改,将此参数发送到ConvertToText子:

Private Sub ExportButton_Click()
    On Error Resume Next
    ConvertToText Me.TextBox1.Value, Me.TextBox2.Value 'Modify this so that it refers to the TextBoxes on your form
    If Err.Number <> 0 Then 
        MsgBox "Unable to convert file. Please ensure a valid file was entered.", vbCritical
    End If
    On Error GoTo 0
End Sub