使用 ADF VBA 将选定的列从一个 sheet 复制到另一个

Copy selective columns from one sheet to another using ADO VBA

我有一个 Summary data sheet 包含带有选择性列名的第一行,我想使用 ADO 填充从 Paste data sheet 中提取的数据。我写了下面的代码:

Sub CreateSummaryData()
Dim oCon As Object, oRec As Object
Dim strSQL As String
Dim wb As Workbook, wk1 As Worksheet, wk2 As Worksheet
Dim xLastColumn As Long, xLastRow As Long, i As Integer
Dim xCell, xRng As Range

On Error Resume Next
Set wb = ThisWorkbook

Set wk1 = wb.Worksheets("Paste Data")
Set wk2 = wb.Worksheets("Summary of data")

Set oCon = CreateObject("ADODB.Connection")
Set oRec = CreateObject("ADODB.Recordset")

With oCon
    .Open Join$(Array("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & _
    wb.FullName & "';Extended Properties=""Excel 12.0; HDR=YES;IMEX=0"""), vbNullString)
End With

With wk2
    xLastColumn = .Range("1:1").Cells(.Columns.Count).End(xlToLeft).Column
    If xLastColumn = 1 Then Exit Sub
    
    Set xRng = .Range(.Cells(1, 1), .Cells(1, xLastColumn))
    
    strSQL = ""
    strSQL = "SELECT "
    For Each xCell In xRng
        strSQL = strSQL & "[" & xCell.Value2 & "],"
    Next xCell
    strSQL = Left(strSQL, Len(strSQL) - 1)
    strSQL = strSQL & " FROM [" & wk1.Name & "$]"
End With

With oRec
    .Open strSQL, oCon, 3, 3
End With

wk2.Range("A2").CopyFromRecordset oRec

With oCon
    .Close
End With

Set oRec = Nothing
Set oCon = Nothing

End Sub

问题是 Paste Data sheet 列的名称之间包含空格或点。我认为这就是 ADO 记录集显示为空并显示“对象关闭时不允许操作”错误的原因。

列名是这样的:

+-----------+---------+---------+------+------------------+-----+-----+-----+-----+-----+------------+------------+------------+------------+------------+------------+
| segmentId | segment | concept | type | metric.base.size | p.5 | p.4 | p.3 | p.2 | p.1 | fitted.p.5 | fitted.p.4 | fitted.p.3 | fitted.p.2 | fitted.p.1 | Mean Value |
+-----------+---------+---------+------+------------------+-----+-----+-----+-----+-----+------------+------------+------------+------------+------------+------------+

我试过使用“[”或“`”来封装列名,但不是很有用。有没有一种方法可以在 ADO 本身中处理这个问题,而无需诉诸于在 Paste dataSummary of data sheets?

中操作列名

如有任何帮助,我们将不胜感激。

编辑:

评论 On error resume next 后,我在断行上收到以下错误,即当它遇到第一个带有“.”的列名时即,metric.base.size:

我也尝试了中给出的解决方案,但出现以下错误:

这是我按照上述 post 格式化后的完整列名。我也尝试用“[”括号和“`”括起来,但得到了同样的错误。是不是因为有不止一个“.”或列中的“ ”?

SELECT `segmentId`,`exerciseConceptId`,`ConceptName`,`ConceptType`,`Groups`,`Segment`,`metric#base#size`,`fitted#p#5`,`fitted#p#4`,`fitted#p#3`,`fitted#p#2`,`fitted#p#1`,`MeanFrequency`,`MeanUnitsFav`,`MeanValue` FROM [Paste Data$]

这对我有用 - 将字段名称中的任何句点替换为 #

For Each xCell In xRng
    strSQL = strSQL & "[" & Replace(xCell.Value2, ".", "#") & "],"
Next xCell

这是您链接的解决方案 post - 您没有显示所有代码,所以我不确定为什么它对您不起作用。