我有一个宏,提示用户选择一个Excel文件,如下所示:
Dim thisBook As Workbook, newBook As Workbook
Dim fd As FileDialog
Dim oFD As Variant
Dim fileName As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xls", 1
.Title = "Choose the Report"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
fileName = oFD
Next oFD
On Error GoTo 0
End With
If fd.SelectedItems.Count = 0 Then
Exit Sub
End If
Set thisBook = ActiveWorkbook
Set newBook = Workbooks.Open(fileName)
这很好,我现在想做什么,以及我在互联网上找不到的内容如下:
我想提示用户从newbook
中选择工作表,因为将来工作表名称可能不同。
我想出了这个,但我对它不是很满意,因为让用户输入工作表名称是相当不方便的:
Function WorksheetExists(WSName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(WSName).Name = WSName
On Error GoTo 0
End Function
Function q() As String
Dim shname As String
Do Until WorksheetExists(shname)
shname = InputBox("Enter sheet name")
If Not WorksheetExists(shname) Then MsgBox shname & " doesn't exist!", vbExclamation
Loop
q = shname
End Sub
是否有办法让用户从所有工作表名称中选择工作表名称? (我没有使用Userform,如果用户单击按钮,则宏启动)
答案 0 :(得分:1)
使用InputBox并让用户选择所需/目标工作表内的任何单元格。将类型设置为8将返回范围。在此范围内,您可以获取工作表及其名称。
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
答案 1 :(得分:0)
使用空白ListBox创建用户表单,并在userform模块中使用此代码
Private Sub UserForm_Initialize()
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
ListBox1.AddItem sh.Name
Next sh
End Sub
Private Sub ListBox1_Click()
Sheets(ListBox1.Value).Activate
Unload Me
End Sub