Advertisement
Guest User

Untitled

a guest
May 25th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. Sub UpdateQueryData(DataSyncSheetName, _
  2. QueryTableName, _
  3. PrimaryKeyHeaderText, _
  4. PrimaryKeyColumn, _
  5. FirstExtraDataColumn, _
  6. LastExtraDataColumn, _
  7. MainSheetName)
  8. ' Assumptions:
  9. ' * External Data has a header row
  10. ' * External Data starts on A1
  11.  
  12. ' Usage:
  13. ' Call UpdateQueryData("DataSync", _
  14. ' "Table_Query_from_external_data", _
  15. ' "PKHeaderText", _
  16. ' "A", _
  17. ' "C", _
  18. ' "F", _
  19. ' "ReportSheet")
  20.  
  21. ' Make sure the connection used is set to disable background refreshes
  22. ' (Data -> Connections -> "ConnectionName" -> Properties -> uncheck Enable background refresh
  23.  
  24. ' DataSyncSheetName : Make sure there is a sheet witht his name
  25. ' to do scratch work (I suggest hiding the sheet)
  26. ' QueryTableName : The name of the query table used. Not sure how to find this other than
  27. ' record macro and select all on that table
  28. ' PrimaryKeyHeaderText : Assumes there is a header with your query data. This is the text
  29. ' to ignore for that header
  30. ' PrimaryKeyColumn : The column that the primary key exists in
  31. ' FirstExtraDataColumn : The first column that contains non-query data (to clear new contents)
  32. ' LastExtraDataColumn : The last column that contains non-query data (to clear new contents)
  33. ' MainSheetName : The name of the sheet holding the query table
  34.  
  35. ' Make sure all the data is recorded
  36. Sheets(DataSyncSheetName).Cells.ClearContents
  37. Range(QueryTableName & "[#All]").Copy
  38. Sheets(DataSyncSheetName).Range("A1").PasteSpecial _
  39. Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
  40. :=False, Transpose:=False
  41.  
  42. ActiveWorkbook.RefreshAll
  43.  
  44. ' For each value in Column A (after the header)
  45. For Each c In Sheets(MainSheetName).UsedRange.Columns(PrimaryKeyColumn).Cells
  46. If Not c.Value = PrimaryKeyHeaderText Then
  47. Set dRange = Sheets(DataSyncSheetName) _
  48. .Range(PrimaryKeyColumn & ":" & PrimaryKeyColumn) _
  49. .Find(c.Value)
  50. If Not dRange Is Nothing Then
  51. dataRow = dRange.Row
  52. For Each d In Sheets(DataSyncSheetName).UsedRange.Rows(dataRow).Cells
  53. If d.Column > 2 Then
  54. Sheets(MainSheetName).Cells(c.Row, d.Column).Value = d.Value
  55. End If
  56. Next d
  57. Else
  58. Range(FirstExtraDataColumn & c.Row & ":" & LastExtraDataColumn & c.Row).ClearContents
  59. End If
  60. End If
  61. Next c
  62. Application.CutCopyMode = False
  63. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement