簡體   English   中英

使用Excel VBA打開工作簿,從certian單元格復制值,保存新表單,然后關閉打開的工作簿

[英]Using Excel VBA to Open a workbook, copy values from certian cells, save the new form, then close the opened workbook

我有一個用於跟蹤項目信息的工作簿。 我一直在更新工作簿功能和宏,但目前沒有辦法將所有用戶輸入的信息傳輸到更新的工作簿。 我正在創建一個“IMPORT”按鈕,允許用戶選擇較舊版本的工作簿,打開該工作簿(wbout),將值復制到新工作簿(wbin),保存新工作簿,然后關閉舊工作簿一個沒有保存它。

此時我遇到了Workbooks.Open命令的麻煩。 具有該命令的行打開工作簿,然后我得到一個

運行時錯誤'91':對象變量或未設置塊變量。

有人可以告訴我做錯了什么嗎? 謝謝

Private Sub ImportPrj1_Click()
Dim rngin As Range
Dim rngout As Range
Dim wsin As Worksheet
Dim wsout As Worksheet
Dim wbin As Workbook
Dim wbout As Workbook
Dim namein As String
Dim folderin As Variant
Dim msg As String

Set wbin = ActiveWorkbook

folderin = Application.GetOpenFilename("Excel-files,*.xlsm", 1, "Select Older Version to transfer information from.", , False)
If folderin = False Then Exit Sub

Application.ScreenUpdating = False

wbout = Workbooks.Open(folderin)  ' <--- Line executes but returns error
Set wsin = wbin.Worksheet("P3 PayOuts")
Set wsout = wbout.Worksheets("P3 PayOuts")
wsin.Range("H4").Value = wsout.Range("H4").Value
wsin.Range("C9:V10").Value = wsout.Range("C9:V10").Value
wsin.Range("K3:K5").Value = wsout.Range("K3:K5").Value
wsin.Range("L3:L5").Value = wsout.Range("L3:L5").Value

' Create File name, save new tracker, close old tracker, make summary active,screen updates = true
namein = InputBox("Enter 1-2 word project identifier to be used in the File Name", "File Name")
namein = "Project Tracker V1.2" & namein
msg = "Project Tracker with imported data will be saved in the same folder as the old version"
msg = msg & vbNewLine & vbNewLine & "File Name: " & namein & ".xlsm"
MsgBox (msg)

Application.DisplayAlerts = False
Application.EnableEvents = False

folderin = Application.wbout.Path
namein = folderin & "\" & namein
NewBook.SaveAs Filename:=namein, FileFormat:=52 ' xlOpenXMLWorkbookMacroEnabled

Workbooks(wbout).Close (False)

With Application
    .DisplayAlerts = True
    .EnableEvents = True
    .ScreenUpdating = True
End With

wbin.Worksheets("Summary").Activate

End Sub

您收到錯誤91因為您在沒有Set關鍵字的情況下分配對象引用,此處:

wbout = Workbooks.Open(folderin)

一旦是固定的,你得到錯誤438,因為你指的是未在上定義的成員Excel.Workbook接口:

Set wsin = wbin.Worksheet("P3 PayOuts")

這是Worksheets ,而不是Worksheet

這兩種錯誤的(也可能是更多的-你必須在有未使用的變量,然后我希望NewBook炸掉一樣)本來是可以避免通過檢查Rubberduck ,一個開源VBIDE外接程序項目我管理。

嘗試將此行輸入上面的代碼“Wbout = Workbooks.Open(folderin)”行:

Tmp = MsgBox(folderin,vbokonly,"folderin:")

如果結果只是一個文件名(例如不是完整路徑),請嘗試以下修改(您可以刪除上面的內容):

Set WBout = Workbooks.Open(WBin.Path & "\" & folderin)

我通常也使用Sheets集合而不是Worksheets ...不確定這是否會改變任何東西,但我過去曾遇到過Worksheets的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM