2009-11-23 158 views
0

我不是很techi-但我一直在录制和编辑基本的Excel宏一段时间。我发现了几个与我的问题几乎一致的结果,但是我正在努力适应它,所以我希望有人能够帮助我?复制和粘贴单元格,如果重复列,Excel宏

我的问题:

表1

A/B/C/d

名/黑/蓝/绿

山姆/ 1 // 1

Jill // 1/

Jill/1 //

萨姆// 1 //

萨姆/ 1/1/1

我有在它重复的名称数据的基础上。我需要去重复这些,只复制一个名称(列a)到一个新页面上,并且在这个过程中我不想丢失一些数据(列bd),这些数据可能是重复名称但不是一个将被复制。

成果,我希望:

表2

A/B/C/d

名/黑/蓝/绿

山姆/ 1/1/1

Jill/1/1/

I h相当多的列搜索数据我的例子是B - D,但它实际上AP - EC所以这将是有益的,如果它是显而易见的,我可能需要改变的数字......?

在此先感谢。

KEZ

+0

始终是数据的数字? – Fionnuala 2009-11-23 15:35:34

+0

是的,它总是1(二进制数据)但是我之前有过这个问题,其中一个包含单词也会更好? :) – 2009-11-23 15:37:52

+0

嗨这看起来不错,谢谢我会放弃它。感谢您的快速回复:) – 2009-11-23 16:30:12

回答

1

你可以尝试ADO,例如:

Dim cn As Object 
Dim rs As Object 
Dim strFile As String 
Dim strCon As String 
Dim strSQL As String 
Dim strWhere As String 
Dim i As Integer 

''http://support.microsoft.com/kb/246335 

''This saves the name of the active workbook, as this is an example, it is best 
''to save before running the code. 
strFile = ActiveWorkbook.FullName 

''This is a standard connection string for Excel and ADO, it depends on strFile 
''being the name of the current workbook, it should be, because that is 
''what the first line does 
''Note also HDR=Yes, this means that the code expects the first row to be headers, 
''in this case, Name, Black, Blue, Green 
''You can get more on connection strings from: http://www.connectionstrings.com/ 
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _ 
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";" 


''This creates the objects needed in the code 
Set cn = CreateObject("ADODB.Connection") 
Set rs = CreateObject("ADODB.Recordset") 

''This opens the connection 
cn.Open strCon 

''This is fairly ordinary SQL, if you are having problems, try a simpler statement 
''such as 
''SELECT * FROM [Sheet3$] 
''It is important that you choose a sheet that exists in the activeworkbook 
''and that the sheet has data. 
strSQL = "SELECT a.[Name], " _ 
     & "(SELECT Max([Black]) FROM [Sheet3$] b WHERE b.[Name]=a.Name) As Black, " _ 
     & "(SELECT Max([Blue]) FROM [Sheet3$] b WHERE b.[Name]=a.Name) As Blue, " _ 
     & "(SELECT Max([Green]) FROM [Sheet3$] b WHERE b.[Name]=a.Name) As Green " _ 
     & "FROM [Sheet3$] a " _ 
     & "GROUP BY a.[Name]" 


''This uses the connection (cn) to open a recordset with the SQL (strSQL) 
''3, 3 refers to the cursor and lock type. 
''More here: http://www.w3schools.com/ADO/met_rs_open.asp 
rs.Open strSQL, cn, 3, 3 

''All this does is put headers in sheet of your choice, I chose sheet5. 
For i = 0 To rs.fields.Count - 1 
    Sheets("Sheet5").Cells(1, i + 1) = rs.fields(i).Name 
Next 

''This copies the recordset into the sheet of your choice, 
''Sheet5 again, in this case 
Worksheets("Sheet5").Cells(2, 1).CopyFromRecordset rs