我不是很聪明 - 但我已经记录和编辑基本的Excel宏一段时间了。我发现了一些几乎与我的问题相符的结果,但是我很难适应它,所以我希望有人可以帮助我?!
我的问题:
第1页
A / B / C / d
名称/黑/蓝/绿
萨姆/ 1 // 1
吉尔// 1 /
吉尔/ 1 //
萨姆// 1 //
萨姆/ 1/1/1
我有一个名称数据库,里面有重复项。我需要对这些进行重复数据删除,只将一个名称(列a)复制到一个新页面上,并且在此过程中我不想丢失一些可能是重复名称但不在的名称的数据(列bd)将被复制的那个。
我希望得到的结果:
第2页
A / B / C / d
名称/黑/蓝/绿
萨姆/ 1/1/1
吉尔/ 1/1 /
我有很多专栏要搜索数据我的例子是b-d但是它实际上是AP-EC所以如果很明显哪些数字我可能需要改变它会有所帮助......?
提前致谢。
KEZ
答案 0 :(得分: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