Excel _使用另一个工作表中的数据更新Sheet中的数据

时间:2016-03-20 15:57:06

标签: excel vba excel-vba macros

成为excel的新手,我无法编写一个宏来更新主数据引用中的一列中的数据。

例如: 我有一张工作表(Tran_Sheet),其中包含交易数据,以及客户的名字和姓氏作为单独的列。

我有另一张Sheet(Master_Data),其中包含客户的所有名字和姓氏。

Tran_Sheet中的数据有噪音和垃圾值,因此有些名称拼写错误。

我需要编写一个宏,以便在Tran_Sheet中根据Master_Data更新名称作为参考。

我知道使用SQL查询这很简单,但我需要在Excel 2013中执行此操作。

谢谢!!!

此致 拉维

2 个答案:

答案 0 :(得分:1)

您可以轻松地在当前工作簿上执行查询:

Sub SQL_Example()

  ' query to compute the average score for each group
  Const SQL_SUM_SCORES_BY_GROUP = _
    "SELECT ref.Group, AVG(data.Score) AS Score " & _
    "FROM [Sheet1$] data INNER JOIN [Sheet2$] ref " & _
    "ON data.Name = ref.Name " & _
    "GROUP BY ref.Group "

  ' execute the query and write the results in a new sheet
  SqlExec ThisWorkbook, SQL_SUM_SCORES_BY_GROUP

End Sub

''
' Executes a query on a workbook.
' @source {Workbook}  Workbook loaded by the SQL engine
' @target {Worksheet} Optional, Worksheet to display the result
' @sql {String} SQL query
''
Sub SqlExec(source As Workbook, sql As String, Optional Target As Worksheet)
  Static rs As Object
  If rs Is Nothing Then Set rs = CreateObject("ADODB.recordset")

  ' build the connection string
  Dim conn$
  conn = "Provider=Microsoft.Jet.OLEDB.4.0" _
       & ";Data Source=" & source.FullName _
       & ";Extended Properties=""Excel 8.0;HDR=Yes"";"

  ' insert a new worksheet if the target worksheet is null
  If Target Is Nothing Then
    Set Target = Worksheets.Add(After:=Worksheets(Worksheets.count))
  End If

  ' execute the query
  rs.Open sql, conn

  ' copy the headers to the target sheet
  Target.Cells.Clear
  For i = 1 To rs.Fields.count
    Target.Cells(1, i).value = rs.Fields(i - 1).name
  Next

  ' copy the values to the target sheet
  Target.Cells(2, 1).CopyFromRecordset rs

  ' dispose
  rs.Close
End Sub

答案 1 :(得分:0)

这绝不是一项简单的任务,无法在SQL查询或Excel中解决,而无需更详细地了解数据中的噪声类型。当它涉及正确的个人数据时,它最终会变成一个骰子,因为它非常非结构化,人们往往会忘记时间组件。