【发布时间】:2013-05-28 02:45:13
【问题描述】:
又一个工作表复制问题!这是一个让我难过的简单问题。我希望单击命令按钮(在 action.xlsm 中)在单独的 excel 文件(inventory.xlsx)中重新填充一个范围内的值(“库存” - 2 列和可能 100 行 - 这是主库存记录) ,来自活动工作表(在 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
这会在wbTarget.wsTarget.Range("A1").Select 行引发“运行时错误'438':对象不支持此属性或方法”
我做错了什么?有什么建议吗?
【问题讨论】:
-
替换它(
wbTarget.wsTarget.Range("A1").Select只用wsTarget.Range("A1").Select- 您定义wsTarget的方式已经暗示了工作簿。我怀疑会这样做。如果您在调试器中运行代码,然后,当您对变量进行“监视”时,您可以确切地看到什么起作用和不起作用...... -
至于您的第一种方法 - 先尝试使用完整路径打开工作簿,然后仅通过名称
inventory.xlsx引用它(而不是整个C:\...事物。 -
谢谢弗洛里斯,成功了!在摆弄了一下之后,我无法让第一种方法起作用。但是在整个代码中正确引用的第二种方法是解决方案。