【发布时间】:2021-05-17 05:16:33
【问题描述】:
personal.xlsb 文件中有一个宏来格式化当前工作表。该宏有两种使用方式
- 在任何打开的文件中按工具栏上的按钮
- 通过从另一个子/过程调用
我正在尝试编写宏,而不使用 SELECT、ACTIVATE、PASTE 等(因此,通过声明所有工作簿和工作表并使用 WITH...)。为此,我必须知道调用宏的文件的名称,并且它必须适用于从按钮和过程中调用。
下面的代码不能完全正常工作,因为它没有在两个工作簿之间切换。我没有完成编码,因为我意识到我不知道如何获取文件和工作表名称。
Option Explicit
Public Sub FormatTheBasics()
Dim CurLastColumn As Long, CurLastRow As Long
Dim CurRowNum As Long, LastRow As Long, FirstRowOfSection As Long, LastRowOfSection As Long
Dim CurCell As Variant, CurRange As Range
Dim wbkM As Workbook, wbkC As Workbook
Dim wksReplaceWords As Worksheet, wksFilesToExportEMail As Worksheet, wksCopyFrom As Worksheet, wksCopyTo As Worksheet
Dim rngCopyFrom As Range, rngCopyTo As Range
Dim x As Long
Dim CurColumnLetter As String, CurColumnName As String, ReplaceFrom As String, ReplaceTo As String
Application.EnableCancelKey = xlDisabled
Set wbkM = Workbooks("Personal.xlsb")
Set wksReplaceWords = wbkM.Sheets("ReplaceWords")
Cells.Select
With Selection.Font
.Name = "Calibri"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Range("A1:" & MyColumnLetter(xlLastCol) & "1").Select
Selection.Font.Bold = True
With Selection.Interior
.PatternColorIndex = 2
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Selection.AutoFilter
Rows("2:2").Select
ActiveWindow.FreezePanes = True
For x = 1 To xlLastCol
CurColumnLetter = MyColumnLetter(x)
CurColumnName = StrConv(Range(CurColumnLetter & "1").Value, vbLowerCase)
Range(CurColumnLetter & "1").Value = StrConv(CurColumnName, vbProperCase)
CurRowNum = 2
With wksReplaceWords
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set CurRange = .Range("C" & CurRowNum & ":C" & LastRow)
For Each CurCell In CurRange
If CurCell <> "" Then
ReplaceFrom = .Range("B" & CurRowNum).Value
ReplaceTo = CurCell
If InStr(1, CurColumnName, ReplaceFrom, vbTextCompare) > 0 Then
Range(CurColumnLetter & "1").Replace what:=ReplaceFrom, replacement:=ReplaceTo, MatchCase:=True
End If
End If
Next CurCell
End With
Next x
Cells.Select
Cells.EntireColumn.AutoFit
Columns("A:" & MyColumnLetter(xlLastCol)).Sort key1:=Range("A2"), order1:=xlAscending, Header:=xlYes
Range("A2").Select
End Sub
【问题讨论】: