简体   繁体   English

Excel VBA:复制所需的数据

[英]Excel VBA: Copying the desired data

I need to write a code that could help copy all the data pertaining to each unique ID into a new CSV file (meaning one CSV file for each unique ID). 我需要编写代码,以帮助将与每个唯一ID有关的所有数据复制到一个新的CSV文件(每个唯一ID意味着一个CSV文件)中。 I'm very new to Excel VBA. 我是Excel VBA的新手。 I am able to copy the entire data into a CSV file. 我可以将整个数据复制到CSV文件中。 However, I fail to do so for each unique ID. 但是,对于每个唯一的ID,我都无法这样做。

在此处输入图片说明

Sub ExportContract(Control As IRibbonControl)
If ThisWorkbook.ActiveSheet.Name <> "Contract" Then
MsgBox "Please Select Contract tab and run again!"
Exit Sub
End If

Application.ScreenUpdating = False
AccountName = ThisWorkbook.Sheets("Information").Range("B4")
Path = Application.ActiveWorkbook.Path
Sheets("Contract").Select
Sheets("Contract").Copy
ActiveWorkbook.SaveAs Filename:=Path & "\" & AccountName & "_Contract.csv", 
FileFormat:=xlCSV, CreateBackup:=False
ActiveWindow.Close
End Sub

Now, this is not the code for this snip. 现在,这不是此片段的代码。 But, this is the real program I will be incorporating the solution you provide, into. 但是,这是我将要结合您提供的解决方案的真实程序。

You need to start at the first cell, move down and export each row. 您需要从第一个单元格开始,向下移动并导出每一行。 As you're exporting to CSV, it is probably easier to export it by writing to a text file, not via "saveas" 当您导出为CSV时,通过写入文本文件而不是通过“ saveas”来导出它可能会更容易

Here is some code to get you started: 以下是一些入门代码:

Public Sub Export()
'//Sort the data first
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A2:B11")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
'//Select the first cell
ThisWorkbook.Sheets(1).Range("A2").Select

Dim sFileName As String
Dim ID As Long
While ActiveCell.Value <> ""        '//Loop until we have gone over all cells
    '//Get the value and file name
    ID = ActiveCell.Value
    sFileName = ThisWorkbook.Path & "\" & ID & ".csv"
    Open sFileName For Output As #1
    '//Keep going until we have dealt with this id
    While ActiveCell.Value = ID
        Print #1, ActiveCell.Value & "," & ActiveCell.Offset(0, 1).Value
        ActiveCell.Offset(1, 0).Select
    Wend
    '//Close that file
    Close #1
Wend

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM