我试着做一件简单的事情。代码应该从一个工作簿复制特定的范围到另一个,但当我运行下面的代码时,复制并没有发生-什么也没有发生。(复制发生在Sub的最后一部分)。我怀疑这可能是工作表/工作簿的问题,但我真的是VBA的新手,所以对我来说很难说...
Function getHeaderRange(searched As String, ws As Worksheet) As Range
Dim colNum
Dim cellLength
colNum = WorksheetFunction.Match(searched, ws.Range("5:5"))
cellLength = ws.Range(ws.Cells(5, colNum), ws.Cells(5, colNum)).MergeArea.Count
Set getHeaderRange = Range(ws.Cells(6, colNum), ws.Cells(6, colNum + cellLength - 1))
End Function
Function getDataRange(searched As String, hRange As Range) As Range
Dim column: column = WorksheetFunction.Match(searched, hRange) + hRange.column - 1
Set getDataRange = Range(Cells(6, column), Cells(6, column))
Debug.Print (hRange.Worksheet.Parent.Name & "Sheet: " & hRange.Worksheet.Name)
Set getDataRange = getDataRange.Offset(1, 0)
Set getDataRange = getDataRange.Resize(8)
End Function
Sub main()
Dim srcWs As Worksheet: Set srcWs = Workbooks("Period end open receivables, step 5").Sheets(1)
Dim trgWs As Worksheet: Set trgWs = ThisWorkbook.Sheets("Obiee")
Dim searched As String
Dim hSearched As String
searched = "Magazines, Merchants & Office"
Dim srcRange As Range: Set srcRange = getHeaderRange(searched, srcWs)
Dim trgRange As Range: Set trgRange = getHeaderRange(searched, trgWs)
Dim cocd() As Variant
Dim i As Integer
cocd = getHeaderRange("Magazines, Merchants & Office", trgWs)
For i = 1 To UBound(cocd, 2)
hSearched = cocd(1, i)
getDataRange(hSearched, srcRange).Copy
getDataRange(hSearched, trgRange).PasteSpecial xlPasteValues
Next i
End Sub
当我将最后几行更改为:
For i = 1 To UBound(cocd, 2)
hSearched = cocd(1, i)
srcWs.Activate
getDataRange(hSearched, srcRange).Copy
trgWs.Activate
getDataRange(hSearched, trgRange).Select
ActiveSheet.Paste
Next i
它工作得很好,但我真的想避免这种方法,并找出什么是错的第一个。帮助真的很感激!
编辑:我在工作簿(1.srcWb,2.trgWb)x1c 0d1x的屏幕截图中添加了一个
文件是巨大的和有区别的,但在这个削减他们是表是相同的。
1条答案
按热度按时间2fjabf4q1#
您的范围未完全限定..
当它们不合格时,Excel将猜测有问题的区域所在的工作表,通常使用当前活动的工作表。这就是为什么您的变通方法在您更改活动工作表时起作用。
该行需要完全合格:
所以它会变成:
此外,该行根本不合格:
所以它会变成: