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

时间:2013-05-28 02:45:13

标签: excel vba copy worksheet

又一个工作表复制问题!这是一个让我难过的简单问题。我希望单击一个命令按钮(在action.xlsm中)重新填充一个范围内的值(“stock” - 2 cols&可能100行 - 这是主库存记录)在一个单独的excel文件中(inventory.xlsx) ),来自活动工作表(在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

上的此属性或方法

我有什么问题?有什么建议吗?

2 个答案:

答案 0 :(得分:1)

替换

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

只是

wsTarget.Range("A1").Select

工作簿已经从您定义wsTarget的方式暗示。我怀疑会这样做。如果您在调试器中运行代码,那么当您对变量进行“监视”时,您可以确切地看到有什么作用,哪些不起作用。

答案 1 :(得分:0)

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

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

stock="A3:B21"

newInventory="A10:B12"