简体   繁体   English

在 vba 为 excel

[英]in vba for excel

In VBA for excel im trying to make hotkeys to modify cell borders.在 VBA for excel 中,我正在尝试制作热键来修改单元格边框。 the hotkey control-shift-Q is supposed to toggle between thick and thin.that part works.热键 control-shift-Q 应该在厚和薄之间切换。那部分有效。 i copied and pasted a recorded macro this.我复制并粘贴了一个录制的宏。 that will draw a bottom thin line.这将绘制一条底部细线。

With Selection.Borders(xlBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin

and replaced .Weight = xlThin with .Weight = var2 , that gives me the error I even tried declaring the variable in the sub, the MSGbox show it right.并将.Weight = xlThin替换为 .Weight .Weight = var2 ,这给了我错误我什至尝试在 sub 中声明变量,MSGbox 显示正确。 then I still get an error any help would be much appreciated.然后我仍然收到错误任何帮助将不胜感激。


    Public var2 As String
    
    Sub keys()
    
    Dim var2 As String
    var2 = "x1Thin"
    
    Application.OnKey "^+q", "thick"
    Application.OnKey "^+x", "down"
    
    End Sub
    
    Sub down()                       'toggle selected cells to have bottom border or erase
    '
    'Dim var2 As String
    'var2 = "x1Thin"
    MsgBox (var2)
    
    If Selection.Borders(xlEdgeBottom).LineStyle = xlNone Then
    'MsgBox ""
        With Selection.Borders(xlEdgeBottom)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = var2                  '<-----this is what is cant get to work
        End With
        
       
    Else
    
    Selection.Borders(xlEdgeBottom).LineStyle = xlNone
    End If
    
    End Sub
    
    Sub thick()
    '
    'Dim var2 As String
    'var2 = "x1Thin"
    
    If var2 = "x1Thin" Then
    var2 = "xlMedium"
    Else
    var2 = "x1Thin"
    End If
    MsgBox (var2)
    End Sub
    
    ""

As Gokhan writes in the comments, xlThin and and xlMedium are numbers (the names are there for convenience and better readability).正如 Gokhan 在评论中所写, xlThinxlMedium是数字(名称是为了方便和更好的可读性)。

Declare your variable as number ( Long ).将您的变量声明为数字 ( Long )。 As the variable should live outside your procedure, easiest (although not the cleanest) way is to declare is as global as you already do:由于变量应该存在于您的过程之外,最简单(虽然不是最干净)的方法是声明 is 和您已经做的一样全局:

Public var2 As Long

But remove the declaration in your subroutine keys , else you will have 2 variables with the same name, but different scope.但是删除子程序keys中的声明,否则您将有 2 个同名但不同的变量 scope。

Assing to the variable (be carefull, you have a type in xlThin , it's an letter l , not the digit 1 :分配给变量(小心,你在xlThin中有一个类型,它是一个字母l ,而不是数字1

If var2 = xlThin Then
    var2 = xlMedium
Else
    var2 = xlThin
End If

Or, shorter:或者,更短:

var2 = iif(var2 = xlThin, xlMedium, xlThin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM