VBA复制Excel范围到不同的工作簿
我正试图find一种方法来将范围复制到另一个工作簿,在这种情况下A6:J21,在一个工作簿中。 我认为这将是如下的东西…
currentWorksheet = xlWorkBook.Sheets.Item("Command Group") excelRange = currentWorksheet.Range("A6:J21") excelDestination = newXlSheet.Range("A6:J21") excelRange.Copy(excelDestination)
但它给我一个excelRange.Copy(excelDestination)
的错误。
下面的代码按预期运行,所以我不知道我在哪里错了。
Dim xRng As Excel.Range = CType(currentWorksheet.Cells(7, 7), Excel.Range) Console.WriteLine(xRng.ToString) Dim val As Object = xRng.Value() testString = val.ToString Console.WriteLine(testString) newXlSheet.Cells(1, 1) = testString
为了回答你的问题“为什么B运行,而不是A”
在A: currentWorksheet = xlWorkBook.Sheets.Item("Command Group")
首先,你丢失了对象分配的SET
。 其次,您正在使用Workbook.Sheets.Item()
返回一个Sheets object
。 一个Sheets object
可以表示一个图表或工作表,因此没有.Range()
方法。
您可以通过跨越此代码来validation这一点:
Dim currentWorksheet As Sheets Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group") excelRange = currentWorksheet.Range("A1:A21")
它会出错,并告诉你,该方法没有find。
解决方法A:确保使用强types打回工作表对象。
Dim currentWorksheet as Worksheet Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group")
为了修复将来的代码并简化debugging过程,我强烈build议在所有模块的顶部始终声明Option Explicit
。
为了简洁起见,您可以将代码缩短为:
Dim currentWorksheet as Worksheet Set currentWorksheet = ThisWorkbook.Sheets("Command Group")
这应该做到这一点,让我知道如果你有麻烦:
Sub foo() Dim x As Workbook Dim y As Workbook '## Open both workbooks first: Set x = Workbooks.Open(" path to copying book ") Set y = Workbooks.Open(" path to destination book ") 'Now, copy what you want from x: x.Sheets("name of copying sheet").Range("A1").Copy 'Now, paste to y worksheet: y.Sheets("sheetname").Range("A1").PasteSpecial 'Close x: x.Close End Sub
或者,您可以:
Sub foo2() Dim x As Workbook Dim y As Workbook '## Open both workbooks first: Set x = Workbooks.Open(" path to copying book ") Set y = Workbooks.Open(" path to destination book ") 'Now, transfer values from x to y: y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 'Close x: x.Close End Sub
从一个工作簿复制并粘贴到另一个