vba - VBA - 代码将粘贴复制到代码中未指定的列中
问题描述
我正在使用下面的代码将combinedWorkbook中的B列复制到ThisWorkbook中的B列,但是在运行宏时,它似乎将B列粘贴到ThisWorkbook的C列中以及粘贴到B列中。我已经逐步完成了代码和它工作正常。这似乎很奇怪,如果它也粘贴到 ThisWorkbook 的 C 列中,将不胜感激。
Sub ImportWriteOffs()
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
' Open BRAM Report Source Data
MsgBox ("Select 'SRMF0035 BRAM Pre Repurchase'")
filter = "Text files (*.*),*.*"
caption = "Select 'SRMF0035 BRAM Pre Repurchase'"
combinedFilename = Application.GetOpenFilename(filter, , caption)
If combinedFilename <> "False" Then
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
Else
MsgBox "No file was uploaded", vbExclamation
GoTo LastLine
End If
If combinedWorkbook.Worksheets(1).Range("D7").Value = "Periodic Insurance" Then
' Copy and Paste into working file
Sheets("Tabular Version").Select
Range("B10:B100000").Select
Selection.Copy
ThisWorkbook.Activate
Sheets("Input - Write offs").Select
Range("B10:B100000").Select
ActiveSheet.Paste
Application.CutCopyMode = False
combinedWorkbook.Close False
' Delete last row
ThisWorkbook.Activate
Sheets("Input - Write offs").Select
Range("B10").Select
Selection.End(xlDown).Select
Selection.EntireRow.Delete
Else
MsgBox "Incorrect File Selected"
combinedWorkbook.Close False
Exit Sub
End If
LastLine:
End Sub
解决方案
你可以试试这个。请注意,您不需要.Select
一个单元格来复制它。它违背了VBA
! 切入正题:说明范围并复制它。无需选择。
此外,不需要GoTo
像臭名昭著的@ashleedawg 所说的那样,只是Exit Sub
在需要的时候。
Sub ImportWriteOffs()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Input - Write offs")
Dim filter As String, caption As String, combinedFilename As String
Dim combinedWorkbook As Workbook, ws2 as Worksheet
MsgBox ("Select 'SRMF0035 BRAM Pre Repurchase'")
filter = "Text files (*.*),*.*"
caption = "Select 'SRMF0035 BRAM Pre Repurchase'"
combinedFilename = Application.GetOpenFilename(filter, , caption)
If combinedFilename <> "False" Then
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
Set ws2 = combinedWorkbook.Sheets("Tabular Version")
Else
MsgBox "No file was uploaded", vbExclamation
Exit Sub
End If
If combinedWorkbook.Worksheets(1).Range("D7") = "Periodic Insurance" Then
ws2.Range("B10:B" & ws2.Range("B" & ws.Rows.Count).End(xlUp).Row - 1).Copy
ws.Range("B10").PasteSpecial xlPasteValues
ws.Range("B10").PasteSpecial xlPasteFormats
combinedWorkbook.Close False
Else
MsgBox "Incorrect File Selected"
combinedWorkbook.Close False
End If
End Sub
推荐阅读
- javascript - 如何使用 mongoose 在深度嵌套的数组上进行切片
- java - JPA - 使用 ElementCollection 在列表中添加和删除元素
- ios - Listview 后台问题
- javascript - 将画布图像转换为 toDataURL() 时未出现滤镜效果
- python - 从 df 中删除一组特征会引发错误:系列的真值不明确
- angular - 角后卫不返回数据
- android-studio - 为什么 DatePicker 返回一个不同的值,然后它正在显示和获取?双向数据绑定 MVVM
- javascript - 不显示本地文件(反应)
- c++ - 智能卡控制代码的 Windows 值格式是什么?
- python - Django mail_admins 从多个电子邮件后端发送