excel - 声明工作簿变量
问题描述
VBA 正在返回一个
运行时 13 错误
当我将工作簿声明为变量然后引用变量来复制数据时
Sub CopyPnLData()
Dim PnLMonth As Workbook
Dim FilePath1 As String
FilePath1 = "C:\Users\mturkenburg\WHISPIR\Gareth Edlin - FP&A\Anaplan\P&L\Monthly Downloads\1.1 P&L OPEX Buckets - Month.CSV"
Workbooks.Open (FilePath1)
Set PnLMonth = Application.Workbooks("1.1 P&L OPEX Buckets - Month.CSV")
Workbooks(PnLMonth).Worksheets("Sheet 1").Range("A1").CurrentRegion.Copy
ThisWorkbook.Worksheets("1.AP Data - P&L").Range("c1").Paste
End Sub
解决方案
我已经修改了您的代码并添加了一些注释供您参考。
Sub CopyPnLData()
Dim PnLMonth As WorkBook
Dim FilePath1 As String
FilePath1 = "C:\Users\mturkenburg\WHISPIR\Gareth Edlin - FP&A\Anaplan\P&L\Monthly Downloads\1.1 P&L OPEX Buckets - Month.CSV"
' check the variable first
If Dir(FilePath1) = "" Then
MsgBox "File not found. : " & FilePath1
Exit Sub
End If
' set your workbook variable when you open it like this
Set PnLMonth = Workbooks.Open(FilePath1)
' use your workbook variable in code like this
PnLMonth.Worksheets("Sheet 1").Range("A1").CurrentRegion.Copy
' not sure if this line is going to work, as you did not provide details about it
ThisWorkbook.Worksheets("1.AP Data - P&L").Range("c1").Paste
' close it when you are done
PnLMonth.Close False
End Sub
推荐阅读
- php - 如何使用外观获取当前会话实例
- c - Libav(ffmpeg)容器编解码器时基和流时基的目的是什么?
- php - 类别和子类别的父 ID
- java - 在 Java 中的 JSON 文件中查找用户输入
- javascript - 如何清除处理文件下载且不导航的 HTML 表单
- java - Unknown mappedBy in:... 引用的属性未知
- laravel - Laravel 8 - 有条件地记住缓存中的值
- javascript - 为什么我的搜索功能不适用于 SpaceX api?
- python - 从以换行符分隔的不同列中的元组列表写入文本文件
- r - 如何计算多个系列的 ACF 并一次绘制它们?