excel 输入框选择工作表和列

ktca8awb  于 6个月前  发布在  其他
关注(0)|答案(2)|浏览(62)

我有一个工作簿上的宏,我想做一个宏,弹出要求我选择工作簿和范围,它做别的事情。
我需要的工作簿名称和范围将在每个工作簿上不同,我使用它,因此为什么我需要它有选择的输入框。

Sub Getsheet()

Dim desiredSheetName As String
desiredSheetName = Application.InputBox("Select any cell inside the target sheet: ", "Prompt for selecting target sheet name", Type:=8).Worksheet.Name
Debug.Print desiredSheetName

MsgBox desiredSheetName

Workbooks(desiredSheetName).Activate

Range("A1") = "TEST"

End Sub

字符串
这只得到工作表名称,而不是工作簿名称,所以在激活行失败。我需要得到工作簿,名称和选定的范围。我相信这是很简单的,但我有点卡住。
谢谢你的帮助。

已关闭

我一定是没说清楚,因为我以为我的要求很简单。
我有一个工作簿,其中将房屋宏,我对各种CVS文件执行。
我打开我的masterwork书和文件,我正在工作,我运行从一个按钮的主工作簿,一个宏。
宏需要拿出一个输入框,使它清晰,直接和简单,让我选择一个范围内的另一个工作簿。
然后我需要使用从输入框中选择的范围运行其余的代码。
我所需要的是如何从选择中获得工作簿名称、工作表名称和范围。
我希望这能消除任何困惑。

5m1hhzi4

5m1hhzi41#

这是我使用的(类似的情况在这里):

Sub test2()
    Dim columnStart As Range
    Dim columnNr As Long
    Dim wbC As Workbook
    Dim wsC As Worksheet
    Dim columnAddress As String
    
    On Error Resume Next
        Set columnStart = Application.InputBox("Select the column with the first key", Default:=Selection.Address(0, 0), Type:=8)
    On Error GoTo 0
    If columnStart Is Nothing Then
        MsgBox "Cancelled."
        Exit Sub
    End If
    Set wbC = columnStart.Parent.Parent
    Set wsC = columnStart.Parent
    columnAddress = columnStart.Address
    columnNr = columnStart.Column
    Debug.Print "Workbook: " & wbC.Name & " with worksheet: " & wsC.Name & " & column Address: " & columnAddress & " with column number : " & columnNr
End Sub

字符串
你得到的范围有一个parent = Workbook,它也有自己的父对象= Workbook。
我的代码的目的是不使它成为我的活动工作簿,而只是获得键列,以便我可以基于它的其余代码。

**编辑:**为您提供更多内容:

Sub Getsheet()

    Dim desiredSheetName As String
    Dim rng As Range
    Set rng = Application.InputBox("Select any cell inside the target sheet: ", "Prompt for selecting target sheet name", Type:=8)
    desiredSheetName = rng.Parent.Name
    Debug.Print desiredSheetName
    
    MsgBox desiredSheetName
    
    rng.Parent.Parent.Activate 'Workbook
    Range("A1") = "TEST"
    'or without needing to use Activate:
    Dim wb As Workbook, ws As Worksheet
    Set wb = rng.Parent.Parent 'isn't really needed here
    Set ws = rng.Parent
    ws.Range("A1").Value = "Test"
End Sub

p5fdfcr1

p5fdfcr12#

所以我可以看到一些关于你如何提示这个问题,但要回答激活工作表的请求,你不必做任何事情.你说,你希望有人点击范围,这将把他们放在该表上。
如果您想从选定的单元格中捕获信息,则有一个选项列表,例如:

Sub test() 'I have the picture below to show the outputs
    Debug.Print Selection.Address
    Debug.Print ActiveSheet.Name
    Debug.Print ActiveWorkbook.Name
End Sub

字符串
因此,如果你想调用一个工作簿,你可以将它们存储为变量,并使用这样的:

Sub test()
    Dim rAddress As Range:  rAddress = Selection.Address
    Dim rSheet As Worksheet:  rSheet = ActiveSheet.Name
    Dim rBook As Workbook:  rBook = ActiveWorkbook.Name
End Sub


然后调用可以是Workbooks(rBook).Sheets(rSheet).Address(rAddress)


的数据

相关问题