简体   繁体   English

Excel VBA 中所需的对象

[英]Object Required in Excel VBA

I am trying to get the user to enter sheet name and based on the input I want selected cell value to be copied from one sheet to another sheet to a new row.我试图让用户输入工作表名称,并根据输入我希望将选定的单元格值从一张工作表复制到另一张工作表到一个新行。

This is for a basic excel functioning system这是一个基本的excel功能系统

Set nextCellInColumn = Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).Offset(1, 0)
strName = Application.InputBox("Please enter")
nextCellInColumn.Value = Worksheets.Application.InputBox("Please enter").Range("I5").Value
Worksheets.Application.InputBox("Please enter").Range("I5").Copy Worksheets("Summary").Range("D6")

You need to test if the worksheet name exists that the user entered otherwise the copy will fail.您需要测试用户输入的工作表名称是否存在,否则复制将失败。 Also if the user presses the Cancel button the InputBox will return a boolean False .此外,如果用户按下取消按钮, InputBox将返回布尔值False You need to check for that and eg exit, or your code fails too.您需要检查并退出,否则您的代码也会失败。

Option Explicit

Public Sub Test()
    Dim wsSummary As Worksheet
    Set wsSummary = ThisWorkbook.Worksheets("Summary")

    Dim NextCellInColumn As Range
    Set NextCellInColumn = wsSummary.Cells(wsSummary.Rows.Count, 4).End(xlUp).Offset(1, 0)

    Dim strName As Variant 'if user presses cancel it will return a boolean false
    strName = Application.InputBox("Please enter")

    If VarType(strName) = vbBoolean And strName = False Then Exit Sub 'user pressed cancel so exit

    If WorksheetExists(strName) Then
        NextCellInColumn.Value = ThisWorkbook.Worksheets(strName).Range("I5").Value
        ThisWorkbook.Worksheets(strName).Range("I5").Copy wsSummary.Range("D6")
    Else
        MsgBox "Worksheet '" & strName & "' not found.", vbCritical
    End If
End Sub

'check if a worksheet exists
Public Function WorksheetExists(ByVal WorksheetName As String, Optional ByVal wb As Workbook) As Boolean
    If wb Is Nothing Then Set wb = ThisWorkbook 'default to thisworkbook

    Dim ws As Worksheet
    On Error Resume Next
    Set ws = wb.Worksheets(WorksheetName)
    On Error GoTo 0

    WorksheetExists = Not ws Is Nothing
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM