让用户从excel中打开的工作簿中选择工作表

时间:2018-10-25 10:26:55

标签: excel vba worksheet

我正在寻求帮助以使Excel询问用户应该选择使用哪个工作簿。我有一本工作簿,其中的按钮链接到宏以执行任务,但是每个月我都需要导入更新的数据。我想同时打开两个工作簿,然后提示用户应该使用哪个工作簿来导入更新的数据。当前,我有允许用户选择要使用哪个工作表的代码,但只能从运行宏的文档中选择。每月工作簿没有标准的命名约定。

Sub Macro6()
'
' Macro6 Macro
'
' 
Const ColItems  As Long = 20
Const LetterWidth As Long = 20
Const HeightRowz As Long = 18
Const SheetID As String = "__SheetSelection"

Dim i%, TopPos%, iSet%, optCols%, intLetters%, optMaxChars%, optLeft%
Dim wsDlg As DialogSheet, objOpt As OptionButton, optCaption$, objSheet As         
Object
optCaption = "": i = 0

Application.ScreenUpdating = False

On Error Resume Next
Application.DisplayAlerts = False
ActiveWorkbook.DialogSheets(SheetID).Delete
Application.DisplayAlerts = True
Err.Clear

Set wsDlg = ActiveWorkbook.DialogSheets.Add
With wsDlg
.Name = SheetID
.Visible = xlSheetHidden
iSet = 0: optCols = 0: optMaxChars = 0: optLeft = 78: TopPos = 40

For Each objSheet In ActiveWorkbook.Sheets
If objSheet.Visible = xlSheetVisible Then
i = i + 1

If i Mod ColItems = 1 Then
optCols = optCols + 1
TopPos = 40
optLeft = optLeft + (optMaxChars * LetterWidth)
optMaxChars = 0
End If

intLetters = Len(objSheet.Name)
If intLetters > optMaxChars Then optMaxChars = intLetters
iSet = iSet + 1
.OptionButtons.Add optLeft, TopPos, intLetters * LetterWidth, 16.5
.OptionButtons(iSet).Text = objSheet.Name
TopPos = TopPos + 13

End If
Next objSheet

If i > 0 Then

.Buttons.Left = optLeft + (optMaxChars * LetterWidth) + 24

With .DialogFrame
.Height = Application.Max(68, WorksheetFunction.Min(iSet, ColItems) *             
HeightRowz + 10)
.Width = optLeft + (optMaxChars * LetterWidth) + 24
.Caption = "Select sheet to go to"
End With

.Buttons("Button 2").BringToFront
.Buttons("Button 3").BringToFront
Application.ScreenUpdating = True

If .Show = True Then
For Each objOpt In wsDlg.OptionButtons
If objOpt.Value = xlOn Then
optCaption = objOpt.Caption
Exit For
End If
Next objOpt
End If

If optCaption = "" Then
MsgBox "You did not select a worksheet.", 48, "Cannot continue"
Exit Sub
Else


Sheets(optCaption).Activate

End If

End If

Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True

End With


End Sub

1 个答案:

答案 0 :(得分:0)

如果要使用工作簿,只需使用类型为== 8(即选择范围)的Application.Inputbox。这样,他们就可以在任何打开的工作簿的任何工作表中选择任何单元格。

工作表是单元格的父级,工作簿是工作表的父级。

dim rng as range, wb as workbook

set rng  = application.inputbox("select a cell on the workbook you want.", type:=8)

debug.print rng.address(0,0)
debug.print rng.address(0,0, external:=true)
debug.print rng.parent.name
debug.print rng.parent.codename
debug.print rng.parent.parent.name
debug.print rng.parent.parent.fullname

set wb = rng.parent.parent
debug.print wb.name
debug.print wb.worksheets(1).name