VBA代码调试请求:按指定行号复制工作表行至目标位置
Fixing Your VBA Copy-Paste Issue
Let's figure out why your code is stalling and get it working as intended:
The main issues with your current code:
- Incorrect quote characters: You’re using full-width Chinese quotes (
“”) for sheet names (likeSheets(“Log”)). VBA only accepts standard half-width English quotes (""), which is almost certainly why your code stops at the copy line — it’s hitting a compilation error it can’t resolve. - Not using the row number from G15: You read the value from
PrintSheet!G15into thevalvariable, but then you hardcodeRows(15)instead of referencingRows(val). So your macro isn’t actually using the row number the user inputs! - Unnecessary
Select/Paste: Using.Selectand.Pasteis error-prone (if the user clicks another sheet while the macro runs, it’ll paste in the wrong place) and less efficient than direct copy-pasting.
Here’s the corrected code:
Sub GetOrder() Dim targetRow As Integer ' Grab the row number from PrintSheet's G15 cell targetRow = Sheets("PrintSheet").Range("G15").Value ' Copy the specified row from Log and paste directly to PrintSheet row 40 Sheets("Log").Rows(targetRow).EntireRow.Copy _ Destination:=Sheets("PrintSheet").Range("A40") End Sub
Quick breakdown of the fixes:
- Swapped all full-width quotes for standard English quotes to eliminate the compilation error.
- Now the macro uses the
targetRowvariable (pulled fromG15) to select which row to copy from the Log sheet, matching your original requirement. - Removed the
.Selectand.Pastesteps by using theDestinationparameter in the.Copymethod — this is a cleaner, more reliable way to handle copy-paste operations in VBA.
内容的提问来源于stack exchange,提问作者Phil Lawson
相关产品推荐
相关产品推荐

