VBA宏Excel导出列,第一行标题显示数据

发布于 2025-01-09 04:23:35 字数 934 浏览 0 评论 0原文

如何导出第一行中存在数据(标题)的所有列?

在此示例图像中,我只想导出存在 "FOO" 的列:

在此处输入图像描述

这是我的代码;

Sub Worksheets_to_txt() 

    Dim ws As Worksheet
    Dim relativePath As String
    Dim answer As VbMsgBoxResult

    relativePath = ActiveWorkbook.Path

    answer = MsgBox("Export in TXT?", vbYesNo, "Run Macro")    
    If answer = vbYes Then

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each ws In ActiveWorkbook.Worksheets

        ws.Select
        ws.Copy
        ActiveWorkbook.SaveAs Filename:= _
        relativePath & "\" & ws.Name & ".txt", _
        FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    Next
     End If

End Sub

谢谢

How can I export all the columns with data present (header) in the first row?

In this example image, I would like to export only the column with "FOO" present:

enter image description here

this is my code;

Sub Worksheets_to_txt() 

    Dim ws As Worksheet
    Dim relativePath As String
    Dim answer As VbMsgBoxResult

    relativePath = ActiveWorkbook.Path

    answer = MsgBox("Export in TXT?", vbYesNo, "Run Macro")    
    If answer = vbYes Then

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each ws In ActiveWorkbook.Worksheets

        ws.Select
        ws.Copy
        ActiveWorkbook.SaveAs Filename:= _
        relativePath & "\" & ws.Name & ".txt", _
        FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    Next
     End If

End Sub

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过期情话 2025-01-16 04:23:35

请将代码的这一部分替换

    For Each ws In ActiveWorkbook.Worksheets

        ws.Select
        ws.Copy
        ActiveWorkbook.SaveAs Filename:= _
        relativePath & "\" & ws.Name & ".txt", _
        FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    Next

为:

   Dim rngDel As Range, lastCol As Long, wsNew As Worksheet, HDRow As Long, i As Long
   For Each ws In ActiveWorkbook.Worksheets
     if ws.Range("A1").value <> "" then
        ws.Copy
        Set wsNew = ActiveWorkbook.Sheets(1)
        'search for the header row:
        For i = 1 To 100
            If WorksheetFunction.CountA(wsNew.rows(i)) > 0 Then
                HDRow = i: Exit For
            End If
        Next i
        lastCol = wsNew.cells(HDRow, wsNew.Columns.count).End(xlToLeft).Column
        'place all cells from the first row, without headers, in a Union range
        For i = 1 To lastCol
            If wsNew.cells(HDRow, i).value = "" Then
                If rngDel Is Nothing Then
                    Set rngDel = wsNew.cells(HDRow, i)
                Else
                    Set rngDel = Union(rngDel, wsNew.cells(HDRow, i))
                End If
            End If
        Next i
        'delete the columns without header, if any:
        If Not rngDel Is Nothing Then rngDel.EntireColumn.Delete
        Set rngDel = Nothing 'preparing the range for the next sheet use
        ActiveWorkbook.saveas fileName:= _
                relativePath & "\" & ws.Name & ".txt", _
                FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    End If
  Next
End Sub

它将没有标题的第一行单元格放置在一个范围中,并在保存工作簿之前立即删除该范围的整个列。

Please, replace this part of your code:

    For Each ws In ActiveWorkbook.Worksheets

        ws.Select
        ws.Copy
        ActiveWorkbook.SaveAs Filename:= _
        relativePath & "\" & ws.Name & ".txt", _
        FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    Next

with this one:

   Dim rngDel As Range, lastCol As Long, wsNew As Worksheet, HDRow As Long, i As Long
   For Each ws In ActiveWorkbook.Worksheets
     if ws.Range("A1").value <> "" then
        ws.Copy
        Set wsNew = ActiveWorkbook.Sheets(1)
        'search for the header row:
        For i = 1 To 100
            If WorksheetFunction.CountA(wsNew.rows(i)) > 0 Then
                HDRow = i: Exit For
            End If
        Next i
        lastCol = wsNew.cells(HDRow, wsNew.Columns.count).End(xlToLeft).Column
        'place all cells from the first row, without headers, in a Union range
        For i = 1 To lastCol
            If wsNew.cells(HDRow, i).value = "" Then
                If rngDel Is Nothing Then
                    Set rngDel = wsNew.cells(HDRow, i)
                Else
                    Set rngDel = Union(rngDel, wsNew.cells(HDRow, i))
                End If
            End If
        Next i
        'delete the columns without header, if any:
        If Not rngDel Is Nothing Then rngDel.EntireColumn.Delete
        Set rngDel = Nothing 'preparing the range for the next sheet use
        ActiveWorkbook.saveas fileName:= _
                relativePath & "\" & ws.Name & ".txt", _
                FileFormat:=xlText, CreateBackup:=False
        ActiveWorkbook.Close
        ActiveWorkbook.Activate
    End If
  Next
End Sub

It places the first row cells without a header in a range and delete this range entire columns at once, before saving the workbook.

南薇 2025-01-16 04:23:35

这是我对这个问题的看法。我没有删除列,而是将它们收集在 ExportRange 中并将其复制到新文件中。

Option Explicit

' Info: Method loops over all worksheets in current Workbook
' and looks for headers with name "Foo". Every column with
' Foo name is exported to the text file with the name of
' that worksheet.

Public Sub Export()

    Dim DataSource As Worksheet
    For Each DataSource In ThisWorkbook.Worksheets

        If DataSource.Range("A1").Value = vbNullString Then
            GoTo NextItem
        End If
    
        Dim Header As Range: Set Header = DataSource.Rows(1).Find("Foo")
        If Header Is Nothing Then GoTo NextItem
        
        ' Understanding where Find method starts is essential
        ' to prevent looping back to the beginning using FindNext method.
        Dim StartAddress As String: StartAddress = Header.Address
        Dim ExportRange As Range
        Set ExportRange = GetColumnData(DataSource, Header.Columns)

        Set Header = DataSource.Rows(1).FindNext(Header)
        Do Until (Header Is Nothing) Or (Header.Address = StartAddress)
            Set ExportRange = Union(ExportRange, GetColumnData(DataSource, Header.Columns))
            Set Header = DataSource.Rows(1).FindNext(Header)
        Loop
        
        ExportRangeToText ExportRange, ThisWorkbook.Path & "\" & DataSource.Name
        
NextItem:
    Next DataSource

End Sub


Private Function GetColumnData(ByVal DataSource As Worksheet, ByVal DataColumn As Range) As Range
        
    Dim LastRow As Long
    LastRow = DataSource.Cells(DataSource.Rows.Count, DataColumn.Column).End(xlUp).Row
    Set GetColumnData = DataColumn.Resize(LastRow, 1)
    
End Function


Private Sub ExportRangeToText(ByVal Rng As Range, ByVal Filename As String)
    
    Dim Export As Workbook: Set Export = Application.Workbooks.Add
    Rng.Copy Export.Worksheets(1).Range("A1")
    Export.SaveAs Filename:=Filename & ".txt", _
                  FileFormat:=xlText, CreateBackup:=False
    Export.Close
    
End Sub

Here is my take on this problem. Instead of removing columns, I'm collecting them in ExportRange and copy it to new file.

Option Explicit

' Info: Method loops over all worksheets in current Workbook
' and looks for headers with name "Foo". Every column with
' Foo name is exported to the text file with the name of
' that worksheet.

Public Sub Export()

    Dim DataSource As Worksheet
    For Each DataSource In ThisWorkbook.Worksheets

        If DataSource.Range("A1").Value = vbNullString Then
            GoTo NextItem
        End If
    
        Dim Header As Range: Set Header = DataSource.Rows(1).Find("Foo")
        If Header Is Nothing Then GoTo NextItem
        
        ' Understanding where Find method starts is essential
        ' to prevent looping back to the beginning using FindNext method.
        Dim StartAddress As String: StartAddress = Header.Address
        Dim ExportRange As Range
        Set ExportRange = GetColumnData(DataSource, Header.Columns)

        Set Header = DataSource.Rows(1).FindNext(Header)
        Do Until (Header Is Nothing) Or (Header.Address = StartAddress)
            Set ExportRange = Union(ExportRange, GetColumnData(DataSource, Header.Columns))
            Set Header = DataSource.Rows(1).FindNext(Header)
        Loop
        
        ExportRangeToText ExportRange, ThisWorkbook.Path & "\" & DataSource.Name
        
NextItem:
    Next DataSource

End Sub


Private Function GetColumnData(ByVal DataSource As Worksheet, ByVal DataColumn As Range) As Range
        
    Dim LastRow As Long
    LastRow = DataSource.Cells(DataSource.Rows.Count, DataColumn.Column).End(xlUp).Row
    Set GetColumnData = DataColumn.Resize(LastRow, 1)
    
End Function


Private Sub ExportRangeToText(ByVal Rng As Range, ByVal Filename As String)
    
    Dim Export As Workbook: Set Export = Application.Workbooks.Add
    Rng.Copy Export.Worksheets(1).Range("A1")
    Export.SaveAs Filename:=Filename & ".txt", _
                  FileFormat:=xlText, CreateBackup:=False
    Export.Close
    
End Sub
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文