自定义功能区按钮打开宏文件,但随后切换焦点

时间:2019-01-21 09:58:18

标签: excel ribbon

我编写了一个Excel宏,该宏可以解析URL列表,并将信息从工作表中保存回每个URL。

我已经在功能区上创建了一个按钮来运行宏。

该宏存储在自己的文件中,因为带有URL的文件每次都是唯一生成的。

当我按下按钮运行宏时,文件未加载。 Excel将加载该文件并打开一个窗口,显示带有空工作表的Macro文件。

然后它将在新打开的宏文件上而不是在我启动宏的URL文件上运行宏。

实际上,URL文件中的第一行中的一两行将由宏处理,然后再切换焦点。

此问题可以解决,因此即使没有首先加载宏文件,也可以通过按钮以正确的方式运行宏?或者,第二种选择是,如果宏文件尚未打开,则将其打开,然后将其停止,不执行任何行?

谢谢托马斯

1 个答案:

答案 0 :(得分:0)

@Luuklag

我找到了使用Workbook Activate的方法。该代码如下所示,包括“修复”。但这并不是一种好的或健壮的方法。

Sub cmdParsePartsList()
Dim iRow As Long
Dim Count As Long
Dim pctCmpl As Integer
Dim TotalCnt As Long

Dim Wb As Workbook
Set Wb = ActiveWorkbook
Wb.Activate    'To move focus back to the TIKA list if pressing the button to start the macro
               'automatically opened the macro file and switched focus to the macro file.
               ' This method does not feel robust. But it is what I came up with.

iRow = 2  'Start at second row, as first row is Heading.
Count = 0 'Counting number of parts written back
pctCmpl = 1

TotalCnt = Application.WorksheetFunction.Subtotal(3, Range("C:C"))

ProgressForm.LabelProgress.Width = 0
ProgressForm.Show

Do Until IsEmpty(Cells(iRow, 3))
    If Not Cells(iRow, 3).Rows.Hidden Then
        Application.StatusBar = iRow
        Call cmdSaveToTika(HLink(Cells(iRow, 3)), Cells(iRow, 5).Text)
        Count = Count + 1

        pctCmpl = ((100 * Count) / TotalCnt)
        With ProgressForm
            .LabelCaption.Caption = "Processing Row " & iRow & " - " & pctCmpl & "%"
            .LabelProgress.Width = (Count / TotalCnt) * (.FrameProgress.Width)
        End With

        DoEvents

    End If
    iRow = iRow + 1
    Wb.Activate         'To move focus back to the TIKA list if pressing the button to start the macro,
                        'automatically opened the macro file and switched focus to the macro file.
                        ' This method does not feel robust. But it is what I came up with.
Loop

Application.StatusBar = "Done with " & Count & " comments saved back to TIKA! :)"
Unload ProgressForm

End Sub