Excel VBA将数据从一个工作表复制到另一个工作表上的另一个用户输入

时间:2016-09-06 18:18:44

标签: excel vba excel-vba macros

我希望我能够彻底搜索到这个问题的答案,然而,在尝试将这些东西放在一起后,我看不到解决方案。我正在尝试根据要开始的行的用户输入将数据从一个工作表复制到另一个工作表。例如,如果他们输入“9”,那么我将添加一个表示该列的字母,并开始将数据复制到另一个单元格。这是代码:

Sub Transfer()

    Dim shSource As Worksheet
    Dim cellValue As Range

    Dim formatedCellBegin As Range
    Dim formatedCellEnd As Range


    Set shSource = ThisWorkbook.Sheets("Sheet1") 'Get info from user input     sheet
    Set cellValue = shSource.Cells(4, "H") 'User input taken from "H4" on sheet1 received in regards  to what row to start transfer


   Set formatedCellBegin = "J" & cellValue 'Add J to the that row to get the cell to start at
   Set formatedCellEnd = "K" & cellValue 'End at cell K - (whatever they pick)


'Sheet 12 is the sheet with all the invoice info
'Sheet 11 is the sheet to put all the info

Sheets("Sheet12").Range("formatedCellBegin:formatedCellEnd").Copy    Destination:=Sheets("Sheet11").Range("B20")
End Sub

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我明白了。因为' formatedCellBegin'而其他被宣称为Strings并不需要设置' Set'在前。

Sub Transfer()

   Dim shSource As Worksheet
   Dim cellValue As Range

   Dim formatedCellBegin As String
   Dim formatedCellEnd As String
   Dim fullRange As String


   Set shSource = ThisWorkbook.Sheets("Sheet10") 'Get info from user input    sheet
   Set cellValue = shSource.Cells(4, "H") 'User input received in regards to what row to start transfer


   formatedCellBegin = ("J" & CStr(cellValue)) 'Add J to the that row to get the cell to start at
   formatedCellEnd = ("K" & CStr(cellValue)) 'End at cell K - (whatever they pick)

   fullRange = formatedCellBegin & ":" & formatedCellEnd

'工作表12是包含所有发票信息的工作表 '表11是放置所有信息的表        ThisWorkbook.Sheets(" Sheet12")。范​​围(fullRange)。复制目的地:= ThisWorkbook.Sheets(" Sheet11")。范​​围(" B20")       结束子

答案 1 :(得分:0)

在您的情况下,您不需要定义 formatedCellBegin formatedCellEnd As Range,但在您的情况下以及如何使用它们时,您需要定义它们{ {1}}。

此外, cellValue 是您从单元格中获取的值,表示一行,因此您需要将其定义为As String(或As Long)。

尝试以下修改后的代码:

Integer