vba 范围类的自动调整方法失败(运行时错误 1004)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28759281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autofit Method of Range Class Failed (Run Time Error 1004)
提问by Benedict Solpico
This is just part of my code. the value from the textbox here already gets copied to the specific cell in the Bank Certification worksheet. I need to make sure that cell C5 is specifically fitted regardless of the length of the text i inputted in the textbox. I tried interchanging range with cells to no avail. This problem seems so simple but I don't know why it doesn't work...
这只是我代码的一部分。此处文本框中的值已复制到银行认证工作表中的特定单元格。无论我在文本框中输入的文本长度如何,我都需要确保单元格 C5 是特别适合的。我尝试用单元格交换范围无济于事。这个问题看起来很简单,但我不知道为什么它不起作用......
Dim counterparty As String
counterparty = Sheet1.txt1.Text
Range("C5").Value = counterparty
Sheets("Bank Certification").Select
Range("C5").Select
Selection.AutoFit
采纳答案by izzymo
Try
尝试
Dim counterparty As String
counterparty = Sheet1.txt1.Text
Range("C5").Value = counterparty
Sheets("Bank Certification").Select
Columns("C:C").Autofit
回答by GlennFromIowa
Other answers correctly state that AutoFit must be used with a column, not just a cell. However, there are some nuances to using AutoFit that I didn't understand until I started experimenting.
其他答案正确指出 AutoFit 必须与列一起使用,而不仅仅是单元格。但是,使用 AutoFit 有一些细微差别,直到我开始试验时我才明白。
Either of the first two statements below will use allvalues in column C to AutoFit the width of the column. That means if there is a value in some other cell in column C (for example C10) that is wider than the value in C5, it will fit the column to the widest cell in column C(for example C10).
下面的前两个语句中的任何一个都将使用C 列中的所有值来自动调整列的宽度。这意味着如果 C 列(例如 C10)中某个其他单元格中的值比 C5 中的值更宽,它将使该列适合C列中最宽的单元格(例如 C10)。
Range("C5").EntireColumn.AutoFit ' Will fit to widest cell in column
Range("C:C").AutoFit ' Will fit to widest cell in column
If you want to justfit the column on 1 cell(or a certain range of cells, but not the whole columnor columns), use a statement like this:
如果你想只适合在列1个单元格(或一定范围内的细胞,但不整列或列),使用这样的语句:
Range("C5").Columns.AutoFit ' Will fit column C to width of cell C5
And of course, it's always better form to write code like this when you can:
当然,如果可以,编写这样的代码总是更好的形式:
- Fully qualify the range unless you're absolutely sure you'll only be working with one worksheet
- Use Named Ranges or Range objects.
- 完全限定范围,除非您绝对确定您将只使用一张工作表
- 使用命名范围或范围对象。
For example:
例如:
Workbooks("MyWorkbook.xlsm").Sheets("Sheet1").Range("MyData").Columns.AutoFit
' or
Set AutoFitRange = Workbooks("MyWorkbook.xlsm").Sheets("Sheet1").Range("C5")
AutoFitRange.Columns.AutoFit