为什么下面的代码在 Excel 工作表中不起作用?此代码根据用户选择将excel文件转换为文本文件,选择可以导出完整的excel表或选定范围,用户也可以选择文本文件的分隔符。我已经在 excel 表单中测试了这段代码,它运行良好,但是如果将用户表单更改为嵌入到 excel 表单中,它就不能完全运行。它确实会生成文本文件,但所有值都是空白的,知道吗?
Public Sub ExportToTextFile(FName As String, SourceFile As String, _
Sep As String, SelectionOnly As Boolean, _
AppendData As Boolean)
Dim wb As Workbook
Dim ws As Worksheet
Dim WholeLine As String
Dim FNum As Integer
Dim RowNdx As Long
Dim ColNdx As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim StartCol As Integer
Dim EndCol As Integer
Dim CellValue As String
StarRange = StrCol & StrRow
EndRange = EndCols & endrows
Application.ScreenUpdating = False
On Error GoTo EndMacro:
FNum = FreeFile
Set wb = Workbooks.Open(SourceFile)
Set ws = wb.Sheets("Sheet1")
If SelectionOnly = True Then
With ActiveSheet.UsedRange
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
Else
With ActiveSheet.Range(StarRange & ":" & EndRange)
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
End If
If AppendData = True Then
Open FName For Append Access Write As #FNum
Else
Open FName For Output Access Write As #FNum
End If
For RowNdx = StartRow To EndRow
WholeLine = ""
For ColNdx = StartCol To EndCol
If Cells(RowNdx, ColNdx).Value = "" Then
CellValue = Chr(34) & Chr(34)
Else
CellValue = Cells(RowNdx, ColNdx).Value
End If
WholeLine = WholeLine & CellValue & Sep
Next ColNdx
WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
Print #FNum, WholeLine
Next RowNdx
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
Close #FNum
MsgBox "Completed.", vbInformation
ActiveWorkbook.Close
End Sub