首页 > 解决方案 > VBA - 最后一列选择和导出

问题描述

我是 VBA 新手,我想做以下事情:

我正在输入不同材料的数据,我会每天添加新材料,每个新材料都有一个新列。

然后我想做的是只选择最新的列条目,然后将其导出为 .txt 文件。

我设法导出了整个工作表,但还没有设法找到如何只导出工作表的最新“条目”。

标签: vba

解决方案


此代码基于在https://www.mrexcel.com/board/threads/vba-to-export-a-specific-worksheet-to-txt-file.754163/#post-3703300发布的示例 John_w并适应您的案子:

选项显式

Public Sub SaveLastColumn()
    Dim rng As Range
    
    Set rng = Worksheets(1).UsedRange           ' get an area with data on the sheet
    Set rng = rng.Columns(rng.Columns.Count)    ' get the last column inside rng
    
    Open "File.txt" For Output As #1            ' open text file for output
    
    If rng.Cells.Count > 1 Then                 ' rng can contains 1 or many cells
        Dim arr As Variant                      ' in case of many cells
        arr = Application.Transpose(rng.Value)
        Print #1, Join(arr, vbCrLf)             ' write many values to file
    Else                                        ' in case of 1 cell
        Print #1, rng.Value                     ' write single value to file
    End If
    
    Close #1
End Sub

推荐阅读