用于从外部工作表更新工作簿的Excel vba代码

又一个工作表复制问题! 这是一个简单的问题,让我难住。 我想单击一个命令button(在action.xlsm)重新填充一个单独的Excel文件(inventory.xlsx)范围内的值(“股票” – 2列和可能100行 – 这是主库存logging)从活动工作表(在action.xlsm中)的已命名范围(“newInventory” – 与其他命名范围的大小相同)中删除原始“库存”值减去缺货项目的值。 计算是好的我只是不能让主库存文件来更新。 我已经检查了一堆论坛,并尝试了两种方法无济于事。 我努力了:

Private Sub CommandButton1_Click() Dim InventoryFileName As String InventoryFileName = "C:\Users\david\Documents\inventory.xlsx" Workbooks(InventoryFileName).Worksheets("Sheet1").Range("stock") = ThisWorkbook.Worksheets("inventory").Range("newInventory").Value Workbooks(InventoryFileName).Save End Sub 

在第4行抛出“运行时错误”9:“下标超出范围”。我也尝试过:

 Private Sub CommandButton1_Click() Dim wbTarget As Workbook 'workbook where the data is to be pasted Dim wsTarget As Worksheet Dim wbThis As Workbook 'workbook from where the data is to copied Dim wsThis As Worksheet Dim strName As String 'name of the source sheet/ target workbook 'set to the current active workbook (the source book) Set wbThis = ActiveWorkbook Set wsThis = ActiveSheet 'get the active sheetname of the book strName = wsThis.Name 'open a workbook that has same name as the sheet name Set wbTarget = Workbooks.Open("C:\Users\david\Documents\" & strName & ".xlsx") Set wsTarget = wbTarget.Worksheets("Sheet1") 'select cell A1 on the target book wbTarget.wsTarget.Range("A1").Select 'clear existing values form target book wbTarget.wsTarget.Range("A1:B10").ClearContents 'activate the source book wbThis.Activate 'clear any thing on clipboard to maximize available memory Application.CutCopyMode = False 'copy the range from source book wbThis.wsThis.Range("A1:B10").Copy 'paste the data on the target book wbTarget.wsTarget.Range("A1").PasteSpecial Paste:=xlPasteValues 'clear any thing on clipboard to maximize available memory Application.CutCopyMode = False 'save the target book wbTarget.Save 'close the workbook wbTarget.Close 'activate the source book again wbThis.Activate 'clear memory Set wbTarget = Nothing Set wbThis = Nothing End Sub 

这将引发“运行时错误438”:对象不支持此属性或方法“在线wbTarget.wsTarget.Range("A1").Select

我错了什么? 有什么build议么?

更换

wbTarget.wsTarget.Range("A1").Select

与刚刚

wsTarget.Range("A1").Select

该工作簿已经隐含了你定义的wsTarget的方式。 我怀疑会这样做。 如果你在debugging器中运行代码,那么当你对variables进行“监视”时,你可以看到究竟是什么和不能工作的。

首先你有2个commandbutton1。 其次,你必须有一个范围的参考,如:

 Workbooks(InventoryFileName).Worksheets("Sheet1").Range("A3:B21") = ThisWorkbook.Worksheets("inventory").Range("A10:B12").Value 

要么

 stock="A3:B21" newInventory="A10:B12"