我编写了一个简单的VBA脚本,该脚本打开给定文件夹中的所有.xls文件,并复制列A。我的愿望是将该信息粘贴到工作簿的唯一列中。我似乎不太容易遍历各列,因此在下面的循环中,我只是将所有内容粘贴到同一列中。我只是不知道如何更新要粘贴到的列。如果我要遍历行,那很简单,它将是Range(“ A”&LastRow),但列似乎比较棘手。在下面的循环中,所有内容都粘贴到目标工作簿的A列(变量wkbDest)中。
Dim wkbDest As Workbook
Dim wkbSource As Workbook 'Source workbooks
Set wkbDest = ThisWorkbook
Const strPath As String = "C:\SecretPath\"
Const sheetName As String = "MacroResults"
Const xlsPattern As String = "*.xls"
ChDir strPath
strExtension = Dir(xlsPattern)
Dim lastColumn As Long 'variable that will be the counter to iterate over the columns
lastColumn = 0
wkbDest.Sheets(sheetName).Cells.Clear
wkbDest.Sheets(sheetName).Range("A1").Value = "Extraction Results"
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath & strExtension)
With wkbSource
lastColumn = lastColumn + 1
wkbSource.Sheets("Test_1").Columns("A:A").Copy
我尝试了wkbDest.Sheets(sheetName).Range("A1").OffSet(0,lastColumn).PasteSpecial
而不是范围Columns(lastColumn)
,但似乎没有任何作用。
wkbDest.Sheets(sheetName).Range("A1").PasteSpecial xlPasteValues
.Close savechanges:=True
End With
strExtension = Dir()
Loop
答案 0 :(得分:1)
将此代码添加到您的代码中,替换粘贴行。
' convert the lastColumn into its letter, and then use it
Dim vArr as Variant, Col_Letter as string
vArr = Split(Cells(1, lastColumn ).Address(True, False), "$")
Col_Letter = vArr(0)
wkbDest.Sheets(sheetName).Range(Col_Letter & "1").PasteSpecial xlPasteValues