【问题标题】:#copy from excel and paste to notepad using VBA#从excel复制并使用VBA粘贴到记事本
【发布时间】:2019-07-09 05:03:42
【问题描述】:

我可以将值从 excel 打印到记事本,但格式有点不同,

Dim txtFile As String, rng As Range, cellValue As Variant, r As Integer, c As Integer
    txtFile = slocation & "\" & "Cont_name_" & Filename & ".txt"
    lrow = Range("I" & Rows.Count).End(xlUp).Row
        Range("A2:G" & lrow).Select
        Set rng = Selection
        Open txtFile For Output As #1
        For r = 1 To rng.Rows.Count
            For c = 1 To rng.Columns.Count
                cellValue = rng.Cells(r, c).Value
                If InStr(cellValue, "/") Then
                    cellValue = Format(cellValue, "yyyyMMDD")
                End If
                If c = rng.Columns.Count Then
                    Print #1, cellValue
                Else
                    Print #1, cellValue,
                End If
            Next c
        Next r
                Close #1

空格超出要求,请帮助实现所需的输出,因为该工具只接受所需的格式

【问题讨论】:

  • 单元格中是否有尾随空格?通常要使用Print 生成固定宽度的列,您会执行类似Print #1, Spc(50 - Len(cellValue)), cellValue 的操作,其中50 是列宽,cellValue 之后是Trim'd。如果输出循环更容易,您也可以使用字符位置。文档是here
  • 没有尾随空格,
  • 看看Fixed Field是不是你要找的?
  • 请在您想要的手动输出下方添加一个比例,1xxx5xxxx0xxxx5xxxx0xxxx5xxxx0xxxx5xxxx0xxxx5 ... 这样我就可以知道所需的间距。我无法将 jpg 转换为 txt 文件。

标签: excel vba notepad


【解决方案1】:

您的第一个输出在每 14 列(位置 1、15、29、...)中使用标准“打印区域”,您可以通过附加 comma 打印获得这些区域

.............|.............|.............|.............|.............|.............|
XXX-XX-XXXX 20190111 AA 123 NAME NAME XXXXX

您想要的输出从下一个 8 个字符的倍数开始(1、9、17、...)

.......|.......|.......|.......|.......|.......|.......|.......|.......|
XXX-XX-XXXX.....20190111........AA......123.....NAME....NAME....XXXXX

您可以通过Seek设置文件中的下一个打印位置

Private Sub SaveAsText()
    Dim rng As Range
    Dim r As Long, c As Long

    Set rng = ActiveSheet.Range("A1:G1")

    Dim file1 As Integer
    file1 = FreeFile
    Open ThisWorkbook.Path & "\test.txt" For Output As file1

    For r = 1 To rng.Rows.Count
        For c = 1 To rng.Columns.Count
            If c = 1 Then
                Print #file1, CStr(rng.Cells(r, c).Value);
            Else
                Seek #file1, (Seek(file1) \ 8 + 1) * 8 + 1
                Print #file1, CStr(rng.Cells(r, c).Value);
            End If
        Next c
    Next r
    Close #file1

End Sub

附加提示:

使用Freefile 获取下一个空闲文件号(可能是1)。

使用CStr() 防止在数值前后自动添加空格字符。

【讨论】:

  • @koti 你试过我的答案了吗?如果它适合您,请考虑将其标记为答案,如here 所述。如果没有,请不要犹豫,在下面发表评论。
  • 是的,可以,但是外部工具还是不能接受文件,因为间距,还是需要四处寻找完美的解决方案
  • 我没有格式化日期,但我希望你这样做。如果您有任何工作示例,您可以在问题末尾复制一行作为文本吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多